Skip to content

Quick Sort ​

Quick sort is a sort that picks one reference value (the pivot), splits the values so that smaller ones go to the left and larger ones to the right, and then sorts both sides again the same way. On average, it is one of the fastest sorts.

At a Glance ​

  • Quick sort sorts an array using the divide and conquer method.
    • Divide and conquer: a strategy that splits a problem into 2 smaller problems, solves each one, and then combines the results to solve the original problem.
  • Analogy: when lining up a class by height, you first pick one student (the pivot) and split everyone into "shorter than me on the left, taller than me on the right." The pivot student's position is then fixed, and you split the left group and the right group again the same way.
  • In terms of classification, it is a comparison sort that sorts using only comparisons with other elements, and an unstable sort in which equal values may change order.
  • Merge sort always splits the array in half, but quick sort splits it unevenly depending on what the pivot value is.

How It Works ​

This is for sorting in ascending order.

  1. Pick one element from the array. This element is called the pivot.
  2. Split the array in two so that elements smaller than the pivot come before it and elements larger than the pivot come after it. This is called Divide. (In the code below, values equal to the pivot go to the left.) Once the split is done, the pivot never moves again.
  3. Repeat this process recursively on the two smaller arrays.
  • Each recursive call fixes the final position of at least one element (the pivot), so the algorithm is guaranteed to finish.

Let's follow the example array [4, 7, 2, 6, 1, 3] with the Python code below (which uses the leftmost value as the pivot). i searches from the left for "a value larger than the pivot," j searches from the right for "a value less than or equal to the pivot," and the two are swapped.

StepRange / pivotArray stateExplanation
StartWhole / 4[4, 7, 2, 6, 1, 3]The leftmost 4 is the pivot
1Whole / 4[4, 3, 2, 6, 1, 7]j stops at 3, i stops at 7 → swap 7 and 3
2Whole / 4[4, 3, 2, 1, 6, 7]j stops at 1, i stops at 6 → swap 6 and 1
3Whole / 4[1, 3, 2, 4, 6, 7]i and j meet. Swap the 1 there with the pivot 4 → 4 is fixed
4Left [1, 3, 2] / 1[1, 3, 2, 4, 6, 7]No value is smaller than 1, so 1 is fixed in place
5[3, 2] / 3[1, 2, 3, 4, 6, 7]Swap the positions of 2 and 3 → 3 is fixed
6Right [6, 7] / 6[1, 2, 3, 4, 6, 7]6 is fixed, 7 is alone so it is done. Sorting complete

In Pictures ​

Quick sort in action

Image source: GimunLee/tech-refrigerator (Apache-2.0)

Python Code ​

Quick sort consists of the following two steps.

Conquer ​

Sort the subarrays. If a subarray is not small enough, apply divide and conquer again through a recursive call.

python
def quick_sort(arr, left=0, right=None, use_mid=False):
    """Quick sort that splits around a pivot and sorts both sides recursively (ascending)"""
    if right is None:
        right = len(arr) - 1
    if left >= right:                              # 1.
        return arr
    pivot = partition(arr, left, right, use_mid)   # 2.
    quick_sort(arr, left, pivot - 1, use_mid)      # 3.
    quick_sort(arr, pivot + 1, right, use_mid)
    return arr
  1. If the range has 0 or 1 elements, it is already sorted, so return right away.
  2. Divide: split the range with partition and receive the position of the pivot, whose place is now fixed.
  3. Conquer: sort the left subarray and the right subarray, excluding the pivot, each with a recursive call.

Divide ​

Split the input array unevenly around the pivot into 2 subarrays (left of the pivot: values less than or equal to the pivot; right: values greater than the pivot).

python
def partition(arr, left, right, use_mid=False):
    """Splits the range in two using the leftmost value as the pivot and returns the pivot's final position"""
    if use_mid:                                    # 1.
        mid = (left + right) // 2
        arr[left], arr[mid] = arr[mid], arr[left]
    pivot = arr[left]                              # 2.
    i, j = left, right
    while i < j:
        while pivot < arr[j]:                      # 3.
            j -= 1
        while i < j and pivot >= arr[i]:           # 4.
            i += 1
        arr[i], arr[j] = arr[j], arr[i]            # 5.
    arr[left] = arr[i]                             # 6.
    arr[i] = pivot
    return i


# Define quick_sort and partition together, then run.
print(quick_sort([4, 7, 2, 6, 1, 3]))
# Output: [1, 2, 3, 4, 6, 7]
print(quick_sort([1, 2, 3, 4, 5, 6, 7], use_mid=True))
# Output: [1, 2, 3, 4, 5, 6, 7]
  1. This is an improvement that avoids the worst case. If use_mid=True, the value at the middle position is moved to the far left and used as the pivot. (This part was commented out in the original Java code. See "Improving the Worst Case" below for details.)
  2. The leftmost value becomes the pivot; i starts at the left end and j at the right end.
  3. Move j to the left to find a value less than or equal to the pivot. Since the pivot itself sits at the far left, j never goes outside the range.
  4. Move i to the right to find a value greater than the pivot. i < j is also checked so that i does not pass j.
  5. Swap the two values found, sending the smaller value to the left and the larger value to the right. Repeat steps 3-5 until i and j meet.
  6. Move the value at the meeting point (a value less than or equal to the pivot) to the far left, and put the pivot in that spot. Now everything left of the pivot is less than or equal to it, and everything to the right is larger.
Watch the recursion depth in Python

Python's default recursion depth limit is about 1000. If you keep using the leftmost pivot as is, an already sorted array of 1000 or more elements makes the recursion as deep as the number of elements, raising a RecursionError. With use_mid=True, using the middle value as the pivot, even a sorted array is split in half each time and works without problems.

Improving the Worst Case ​

In partition(), if the pivot turns out to be the minimum or maximum of the range and everything goes to one side, the time complexity becomes O(n²).

In other words, the code above, which uses the leftmost value as the pivot, is O(n²) when the array is already sorted in ascending or descending order. In that case, swapping the first value with the value at the middle position before using it as the pivot (use_mid=True) splits even a sorted array evenly, improving most cases to O(n log₂ n). However, even with this improvement, the worst-case time complexity of quick sort does not become O(n log₂ n). For an array arranged so that the middle value happens to be the minimum or maximum, it is still O(n²). Choosing the pivot at random is also widely used, but it does not eliminate the worst case either; it only makes the worst case very unlikely.

Time and Space Complexity ​

Best Case : T(n) = O(n log₂ n) ​

  • Depth of recursive calls (log₂ n)

    Assume the number of records n is a power of 2 (n = 2^k). If n = 2³ and the pivot splits exactly in half every time, the size shrinks as 2³ → 2² → 2¹ → 2⁰, so the depth of recursive calls is 3.

    Recursion depth of quick sort in the best case

    Image source: GimunLee/tech-refrigerator (Apache-2.0)

    Generalizing this, when n = 2^k the depth is k (k = log₂ n).

  • Comparisons at each level of recursion (n)

    At each level, almost every record in the whole list must be compared, so there are about n comparisons on average.

So the best-case time complexity is depth of recursive calls × comparisons at each level = n log₂ n. The number of moves (swaps) is smaller than the number of comparisons, so it can be ignored.

Worst Case : T(n) = O(n²) ​

The worst case is when the pivot is the minimum or maximum every time. If the leftmost value is used as the pivot, this happens when the array to be sorted is already sorted in ascending or descending order. (With the code above, an array where every value is the same also splits only to one side and hits the worst case.)

  • Depth of recursive calls (n)

    Recursion depth of quick sort in the worst case

    Image source: GimunLee/tech-refrigerator (Apache-2.0)

    Each split reduces the elements by only 1, so the depth of recursive calls is n.

  • Comparisons at each level of recursion (n)

    At each level, almost every record in the whole list must be compared, so there are about n comparisons on average.

So the worst-case time complexity is depth of recursive calls × comparisons at each level = n². The number of moves is smaller than the number of comparisons, so it can be ignored.

Average Case : T(n) = O(n log₂ n) ​

For a random array, it is rare for the pivot to land at one extreme, so on average it is O(n log₂ n), the same as the best case.

Summary by Case ​

CaseTime complexity
BestO(n log n)
AverageO(n log n)
WorstO(n²)
SpaceRecursion call stack: O(log n) on average, O(n) in the worst case
  • Space: it only swaps within the array, so it does not create separate arrays. However, it uses memory as recursive calls pile up, so the extra memory equals the recursion depth: O(log n) on average, O(n) in the worst case. (If you recurse into the smaller of the two parts first and handle the larger part with a loop, you can reduce it to O(log n) even in the worst case.)
  • For Big-O notation, see the time complexity article.

Pros and Cons ​

Pros ​

  • It reduces unnecessary data movement, swaps far-apart data in one step, and removes each pivot from later operations once its position is fixed, so in practice it tends to be the fastest even among O(n log n) sorts.
  • It swaps within the array being sorted, so there is no need to create a separate array. (It only uses the recursion call stack in addition.)

Cons ​

  • It is an unstable sort.
  • On an already sorted array, it splits unevenly and actually takes longer to run. (When the leftmost value is chosen as the pivot.)

Let's look at an unstable example. We label two equal values 2 as 2a and 2b.

StepArray stateExplanation
Start[2a, 2b, 1]2a comes before 2b. The pivot is 2a
Divide[1, 2b, 2a]i and j meet at the end (1), and 1 is swapped with the pivot 2a

The sort is finished, but the order of 2a and 2b has been reversed.

Wrapping Up ​

We looked at quick sort, one of the fastest sorting algorithms on average. It is efficient enough that Java's Arrays.sort() uses Dual-Pivot Quick Sort (a quick sort with 2 pivots) for primitive arrays such as int[]. (For object arrays, it uses Timsort, a stable sort.) It is a topic that comes up very often in technical interviews, so it is well worth mastering. If you need a sort that guarantees O(n log n) even in the worst case, also look at merge sort and heap sort.

Summary ​

ConceptPlain-language summary
Quick sortStand one person up as the reference, split into a smaller side and a larger side, and sort each again
PivotThe reference value that splits the groups. Once the split is done, its own position is fixed
Divide and conquerBreak a big problem into small ones, solve them and combine the results
Worst caseIf the reference is always the value at an extreme, everything goes to one side and it slows down
Middle pivotChoose the reference from the middle so even a sorted array splits in half

Source: GimunLee/tech-refrigerator (Apache-2.0), code rewritten in Python

Reference: jinhyy - Sorting Algorithms