Quick sort picks one value, the pivot, puts smaller values left of it and the rest right, so the pivot lands in its final place. Then it does the same to each side.

Quick check

Quick check: The first pivot is 7. Six values in the list are smaller than 7. At which index does 7 land?

Why the pivot is already home#

After the first split, the list looks like this. 7 sits at index 6.

521346798100123456789
after the first split, pivot 7

Everything left of 7 is smaller and everything right of it is bigger. Sorting the left side only shuffles those six values among indexes 0 to 5. Sorting the right side only touches indexes 7 to 9. No value ever crosses over 7, so 7 never moves again. The left and right sides are now two smaller, separate problems.

One split, step by step#

This way of splitting is the Lomuto partition. The pivot is the last value. i marks the end of the small side, and j scans every other value. When a[j] is smaller than the pivot, the small side grows by one and a[j] swaps into it. At the end, the pivot swaps into slot i + 1, right after the small side.

Partition around the last valueline 1
Try another last
  1. last = 4
  2. a = [5, 2, 8, 1, last]
  3. p = a[-1]
  4. i = -1
  5. for j in range(len(a) - 1):
  6. if a[j] < p:
  7. i += 1
  8. a[i], a[j] = a[j], a[i]
  9. a[i+1], a[-1] = a[-1], a[i+1]
  10. print(a, "pivot at", i + 1)

Variables

last
4 (just changed)

The last value in the list will be the pivot.

Step 1 of 19

Quick check

Quick check: Move the last slider to 0, smaller than every other value. Where does the pivot land?

The full code#

Split, then sort each side with the same function. That is recursion, which you met in the space complexity step. lo and hi are the first and last index of the part being sorted. The left side is lo to i. The right side starts at i + 2, because the pivot at i + 1 is already done.

Quick sort, line by lineline 1
  1. def qs(a, lo, hi):
  2. if lo >= hi: return
  3. p, i = a[hi], lo - 1
  4. for j in range(lo, hi):
  5. if a[j] < p:
  6. i += 1
  7. a[i],a[j]=a[j],a[i]
  8. a[i+1],a[hi]=a[hi],a[i+1]
  9. qs(a, lo, i)
  10. qs(a, i + 2, hi)
  11. a = [3, 1, 4, 2]
  12. qs(a, 0, len(a) - 1)

Variables

None yet

Line 1 runs.

Step 1 of 33

Line 2 is the base case: it stops a call when the part is empty (like 2 to 1) or has one value (like 0 to 0).

Quick check

Quick check: What would happen without line 2?

How fast is it#

Each level of splitting looks at every value once, so a level costs about n steps. The question is how many levels there are.

  • Best case, O(n log n). Every pivot is the middle value of its part, so each split is an even half. Halving n again and again reaches 1 after about log n steps, like binary search, so there are about log n levels.
  • Average case, O(n log n). On random input the splits are uneven but not terrible, and it still works out to O(n log n).
  • Worst case, O(n²). An already sorted list with the last value as pivot. The pivot is always the biggest, so every split is n - 1 and 0.

Here is the worst case on [1, 2, 3, 4, 5]:

PartPivotComparisonsNext part to sort
1 2 3 4 5541 2 3 4
1 2 3 4431 2 3
1 2 3321 2
1 2211

That is 4 + 3 + 2 + 1 = 10, which is n(n - 1)/2. A reverse sorted list is just as bad. So is a list where every value is equal, because with < no value goes to the small side.

Quick check

Quick check: IRCTC gives you 10,000 PNR numbers, already sorted. About how many comparisons does this quick sort make?

Fixing the worst case#

The fix is a random pivot: pick a random index in the part, swap it to the end, then partition as before.

Python

Now no input of distinct values can force bad splits. The average time over the random picks is O(n log n) for any such input, and O(n²) needs very bad luck. Lists full of repeats still need a three-way partition (values less than, equal to, and greater than the pivot).

Quick check

Quick check: With a random pivot, what does sorted input cost on average?

Space, in place and stable#

Quick sort is in place: it only swaps values inside the list and needs no second array. The extra space is the call stack. That is O(log n) on average, since there are about log n levels. On the worst case it grows to O(n).

It is not stable. Two students on the same marks can swap order. Watch Asha and Ravi, both on 72:

Asha and Ravi swap places

marks

namemarks
Asha72
Neha65
Ravi72
  • Same marks

Asha comes before Ravi. The pivot is the last row, Ravi 72.

Step 1 of 3

The final pivot swap threw Asha to the end, past Ravi. Long swaps like this break the order of equal values.

Quick sort or merge sort#

Quick sortMerge sort
Best, averageO(n log n)O(n log n)
WorstO(n²)O(n log n)
Extra spaceO(log n) stackO(n)
StableNoYes
In placeYesNo

Use quick sort for numbers in an array when stability does not matter. Use merge sort when you need stability, a guaranteed O(n log n), or you are sorting a linked list.

Quick check

Quick check: Same O(n log n). Why does quick sort usually beat merge sort on an int array?

Real libraries use it, with care. Java sorts primitive arrays like int[] with dual-pivot quicksort (two pivots, three parts). For objects it uses TimSort, a kind of merge sort, because objects must stay stable. C's qsort is named after quick sort, but the C standard does not fix the algorithm, and libraries differ.

The same code in four languages#

Here is quick sort with the Lomuto partition in Python, C++, Java and Go. It uses <= instead of <. Both sort correctly. With <=, equal values join the small side, and all equal values still give the n - 1 and 0 worst case.

One last check#

Quick check

Quick check: Quick sort on [4, 9, 2, 7, 5], pivot = last value. What is true after the first partition?

Next you drive the quick sort visualizer on your own inputs, to see where each pivot lands before the readiness check tests all five sorts.