This sample has no "java" implementation. Showing another one instead.

Algorithms

Partition around a pivot (Lomuto scheme, last element) and sort each side — O(n log n) on average.

Version 1.0.0 Versions: 1.2.0 1.1.0 1.0.0

This is an older version. The current version is 1.2.0.

Implementations

Sign in to open in IDE Sign in with your Zerethon account to create your own copy of this sample.

Files

README.md
# Quick Sort

Zerethon Official Sample `quick-sort`, version 1.0.0, Python 3.12.

- `quick_sort.py` — the algorithm, as shown in Zerethon Tools
- `main.py` — entry file: a short demonstration
- `test_quick_sort.py` — checks; set it as the entry file to run them

This project is your own copy. Changing it never changes the official sample.
See the algorithm animated: https://tools.zerethon.com/quick-sort-visualizer
main.py entry
from quick_sort import quick_sort

numbers = [38, 27, 43, 3, 9, 82, 10, 27]
print("Before:", numbers)
result = quick_sort(list(numbers))
print("After: ", result)
print("Same as sorted():", result == sorted(numbers))
quick_sort.py
"""Quick Sort (Zerethon Official Sample: quick-sort 1.0.0)."""


def quick_sort(a, lo=0, hi=None):
    if hi is None:
        hi = len(a) - 1
    if lo >= hi:
        return a
    pivot = a[hi]
    i = lo
    for j in range(lo, hi):
        if a[j] < pivot:
            a[i], a[j] = a[j], a[i]
            i += 1
    a[i], a[hi] = a[hi], a[i]
    quick_sort(a, lo, i - 1)
    quick_sort(a, i + 1, hi)
    return a
test_quick_sort.py
# Checks for quick_sort. To run them, set this file as the entry file
# (the ▶ button next to it in Files) and press Run.
from quick_sort import quick_sort


def numbers(seed, count):
    """Deterministic pseudo-random integers in [-50, 49]."""
    out = []
    for _ in range(count):
        seed = (seed * 1103515245 + 12345) % 2**31
        out.append(seed % 100 - 50)
    return out


cases = [[], [1], [2, 1], [1, 2, 3], [3, 2, 1], [5, 1, 5, 1, 5], [-3, 0, -1, 2]]
cases += [numbers(seed, size) for seed, size in ((1, 10), (2, 50), (3, 200))]

for case in cases:
    got = quick_sort(list(case))
    assert got == sorted(case), f"quick_sort({case[:6]}...) = {got[:6]}..."

print(f"All {len(cases)} checks passed.")

Source: Zerethon Official Sample. Algorithm as shown in the Zerethon Tools Quick Sort Visualizer.