Interactive demo

Quicksort Visualization

Quicksort is a widely used sorting algorithm based on divide and conquer. It needs O(n log n) steps on average and O(n²) in the worst case.

Your browser does not support the HTML5 canvas tag.

Press “Next Step” to advance one step at a time, or “Play” to run the algorithm on its own. Try different starting orders below the buttons.

Playback

Comparisons
0
Writes
0

Array

Legend

  • Unsorted element
  • Pivot
  • “lower” arrow
  • “greater” arrow
  • Final position

Runtime and properties

Best case

O(n log n)

Every pivot splits its section into two halves of equal size.

Average case

O(n log n)

Pivots split well enough on average: about log n levels with n comparisons each.

Worst case

O(n²)

The pivot is always the smallest or largest element, so each level only removes one element.

Extra memory

O(log n)

Only the recursion stack, as long as the smaller part is sorted first.

Stable

No

Swaps over long distances can change the order of equal elements.

In-place

Yes

Elements are only swapped within the array.

n is the number of elements. O(n log n) is the best a sorting algorithm based on comparisons can achieve.

Compared with the other sorting algorithms

AlgorithmBest caseAverage caseWorst caseExtra memoryStableIn-place
Bubble sortO(n)O(n²)O(n²)O(1)YesYes
Selection sortO(n²)O(n²)O(n²)O(1)NoYes
Insertion sortO(n)O(n²)O(n²)O(1)YesYes
Shell sortO(n log n)≈ O(n1.25)O(n1.5)O(1)NoYes
Tree sortO(n log n)O(n log n)O(n²)O(n)YesNo
Tournament sortO(n log n)O(n log n)O(n log n)O(n)YesNo
HeapsortO(n log n)O(n log n)O(n log n)O(1)NoYes
SmoothsortO(n)O(n log n)O(n log n)O(1)NoYes
Merge sortO(n log n)O(n log n)O(n log n)O(n)YesNo
Patience sortO(n)O(n log n)O(n log n)O(n)YesNo
TimsortO(n)O(n log n)O(n log n)O(n)YesNo
Block sortO(n)O(n log n)O(n log n)O(1)YesYes
Quicksort this pageO(n log n)O(n log n)O(n²)O(log n)NoYes
IntrosortO(n log n)O(n log n)O(n log n)O(log n)NoYes
FluxsortO(n)O(n log n)O(n log n)O(n)YesNo
CrumsortO(n)O(n log n)O(n log n)O(log n)NoYes

1. Pick a pivot

One element of the current section is chosen as the pivot and moved to the end of that section.

2. Partition

Two arrows walk toward each other and swap elements until everything smaller than the pivot is on the left and everything larger is on the right.

3. Recurse

The pivot moves to its final position and is marked as finished. The same steps then repeat for the left and the right part until the array is sorted.