Algorithms
Quick Sort
O(n log n) time on average · O(n²) time in the worst case, with bad pivot choices · O(log n) space for the recursive calls.
The idea, in plain English
Quick sort picks one item as a 'pivot' — a reference point for splitting the list. It puts the rest into two buckets: smaller-than-pivot and bigger-than-pivot. Then it sorts each bucket the same way. It is like organizing papers by placing each one to the left or right of a chosen middle paper.
How it works
- 1Pick a pivot item from the list.
- 2Put everything smaller on its left, and everything bigger on its right.
- 3Repeat the same process on the left and right groups, then join them together.
When you'd use it
This is a common general-purpose sort. It is fast in practice and sorts in place, using little extra memory.
Common beginner mistakes
- Always picking the first item as the pivot. On already-sorted data, that gives you the slow worst case.
- Making off-by-one errors when you split the list into the two groups.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Before: 5 2 9 1 5 6
Sorted: 1 2 5 5 6 9See it in motion
Ready. Press play to watch it sort.
Not sure this is the right topic? See the learning paths → or where this leads →