Skip to content
UPEEC

Quick Sort

Pick a pivot, partition smaller and larger elements around it, and recurse.

Intermediate
Comments 0
def quick_sort(a, lo=0, hi=None):
    if hi is None:
        hi = len(a) - 1
    if lo < hi:
        pivot, i = a[hi], 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)

Average O(nlog⁡n)O(n \log n), sorts in place and is very fast in practice. A bad pivot (e.g. already-sorted data with the last element as pivot) gives O(n2)O(n^2); random or median-of-three pivots avoid this.

Spotted a mistake or want to add detail? Suggest an improvement — Content Contributors' edits are reviewed by editors before they go live.

Discussion (0)

Sign in or join free to ask questions and discuss this topic.