Quick Sort Visualization: Pivot and Partition Step by Step

Quick sort picks a pivot, partitions the list so smaller items go left and larger items go right, which puts the pivot in its final position, and then sorts each side recursively.

About this visualization

Quick sort picks a pivot, rearranges the list so smaller items are on its left and larger items on its right (partitioning), which places the pivot in its final position, then sorts each side. It is usually the fastest general-purpose comparison sort in practice.

How it works

  1. Choose the last item of the range as the pivot (Lomuto partition).
  2. Move every item smaller than the pivot to the left side.
  3. Place the pivot between the two sides, then recurse on each side.

Worked example

Sort [4, 2, 7, 1] with the last item as pivot. Pivot 1: nothing is smaller, so it swaps to the front → [1, 2, 7, 4] and is final. Sort [2, 7, 4] with pivot 4: 2 < 4 stays left, 7 does not, pivot swaps with 7 → [2, 4, 7]. The final list is [1, 2, 4, 7].

Enter these numbers in the simulator above to see every step.

Complexity and properties

Best caseO(nlog⁡n)O(n \log n)
Average caseO(nlog⁡n)O(n \log n)
Worst caseO(n2)O(n^{2})
SpaceO(log⁡n)O(\log n)
StableNo
In-placeYes

Worst case happens on already sorted input with a last-item pivot; space is the recursion stack.

When to use it

  • Understanding partitioning, the key idea behind many selection and sorting algorithms.
  • Seeing why a bad pivot gives the O(n2)O(n^{2}) worst case.
  • Comparing quick sort with merge sort and heap sort.

Frequently asked questions

What is the time complexity of quick sort?

O(nlog⁡n)O(n \log n) on average and in the best case, O(n2)O(n^{2}) in the worst case (for example a sorted list with the last item as pivot). Space is O(log⁡n)O(\log n) for the recursion stack.

Is quick sort stable?

The standard in-place version is not stable.

How can the worst case be avoided?

Choose the pivot randomly or as the median of three items instead of always taking the last item.