Algorithms · Visualized
Quick Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Quick Sort is another divide-and-conquer algorithm. Time: O(n log n) average, O(n²) — happens with a poor pivot choice, e.g. already-sorted input with a fixed pivot worst; space: O(log n) — recursion stack, sorts in place.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Quick Sort
SortingQuick Sort is another divide-and-conquer algorithm. It picks a 'pivot' element, rearranges (partitions) the array so everything smaller than the pivot ends up on its left and everything bigger ends up on its right, then recursively sorts each side.
How Quick Sort Works
- Pick a pivot element from the array (common choices: first, last, middle, or random element).
- Partition the array: move all elements smaller than the pivot to its left, and all bigger elements to its right — the pivot lands in its final sorted position.
- Recursively apply the same process to the left sub-array (elements less than the pivot).
- Recursively apply the same process to the right sub-array (elements greater than the pivot).
- Once sub-arrays of size 0 or 1 are reached, the array is fully sorted.
Quick Sort Worked Example
Input: [10, 80, 30, 90, 40, 50, 70]
Pick last element 70 as pivot. Partition: elements less than 70 (10,30,40,50) go left, greater (80,90) go right → [10,30,40,50,70,90,80], pivot 70 now fixed. Recurse left [10,30,40,50] and right [90,80], sorting each the same way, until the full array is sorted: [10,30,40,50,70,80,90].
def quick_sort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo >= hi:
return
p = a[hi]
i = lo
for j in range(lo, hi):
if a[j] < p:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
quick_sort(a, lo, i - 1)
quick_sort(a, i + 1, hi)
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Quick Sort Time & Space Complexity
When to Use Quick Sort
- General-purpose sorting — often the fastest in practice for arrays, used in many standard libraries.
- When average-case speed matters more than worst-case guarantees.
- Foundation for the related Quickselect algorithm for finding the k-th smallest element.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.