Developer Toolbox

Quicksort

Picks one value, the pivot, and moves smaller values to its left and bigger ones to its right. Then it does the same for each side.

  • Ω(n log n)
  • Θ(n log n)
  • O(n²)
  • O(log n)
  • no
  • yes
  • comparing
  • moving
  • pivot
  • in final place
0 / 187 steps

Recursion depth: 0 · least possible: 4 · worst: 23 waiting for its pivot

Comparisons Swaps

Press play: the lines show how the cost grows as the sort runs

Press play or step through the algorithm.

Space: play or pause. Left and right arrows: step. Home and End: jump.

Try this: Pick a reversed list. The pivot is always the smallest or the biggest value left, so one side of every split is empty and the cost climbs towards n².

How it works

Here the pivot is the last value of the range. Going from left to right, every value that is not bigger than the pivot is swapped into the left part. Then the pivot goes between the two parts, where it stays for good. Each part is then sorted the same way.

When it is a good choice

One of the fastest ways to sort in practice, and it needs almost no extra memory. But if it keeps picking a bad pivot, for example on a list that is already sorted, it becomes slow. Real versions choose the pivot more carefully.