Quick sort
Explore the quick sort algorithm, a divide-and-conquer method that sorts arrays by choosing a pivot and recursively partitioning elements. Understand how pivot choice affects performance and learn the JavaScript implementation of this efficient in-place sorting technique.
Imagine a teacher asks students to line up around a chosen benchmark height. Everyone shorter than the benchmark stands on the left, everyone taller than the benchmark stands on the right, and then each side repeats the process with its own benchmark.
That is the core idea of quick sort. Instead of merging sorted halves like merge sort, quick sort repeatedly partitions the array around a pivot element.
Quick sort is a divide-and-conquer sorting algorithm that chooses a pivot, partitions the array so smaller elements go left, and larger elements go right, then recursively sorts the two partitions.
Why it is called “quick”: On average, quick sort produces balanced partitions and sorts efficiently with low constant overhead. That is why it performs well in practice.
How it works
Quick sort usually has three conceptual steps:
Choose a pivot.
Partition the array so values smaller than the pivot move left and values larger move right.
Recursively sort the left and right partitions.
The partition step is the heart of the algorithm. Once the pivot lands in its correct final position, it never needs to move again.
Important: The algorithm’s speed depends heavily on pivot choice. Good pivots create balanced partitions. Bad pivots create uneven partitions and can cause worst-case performance.
Interactive animation
This visualizer focuses on the partition idea. It highlights the pivot and shows how smaller and larger values conceptually separate around it.
Algorithm
Before writing JavaScript code, read through the algorithm and connect each step to the trace above.
If the list has one element or is empty:
It is already sorted, so return.
Otherwise:
Choose a pivot element (commonly the last element).
Partition the list around the pivot:
Initialize a pointer
ito track the boundary of smaller elements.Traverse the list from left to right (excluding the pivot):
For each element:
If it is smaller than the pivot:
Move the boundary forward.
Swap the current element with the element at the boundary.
After traversal:
Place the pivot in its correct position by swapping it with the next boundary position.
Recursively apply quick sort:
Sort the left portion (elements ...