Overview
Quick Sort is one of the most efficient sorting algorithms in practice. It uses a divide-and-conquer strategy: select a “pivot” element, partition the array so elements smaller than the pivot are on the left and larger elements are on the right, then recursively sort the two partitions.Complexity
- Time Complexity:
- Best case: O(n log n) - balanced partitions
- Average case: O(n log n)
- Worst case: O(n²) - already sorted or all elements equal (with bad pivot selection)
- Space Complexity: O(log n) - due to recursion stack
- Stable: No - may change relative order of equal elements
Implementation
Here’s the actual implementation from the Sorting Algorithms Visualiser:How It Works
The Partition Function
- Select Pivot: Choose the last element
nums[high]as the pivot - Initialize pointer: Set
i = low - 1(tracks the boundary of smaller elements) - Scan array: Loop through elements from
lowtohigh - 1:- If
nums[j] <= pivot: incrementi, swapnums[i]andnums[j] - This moves elements ≤ pivot to the left side
- If
- Place pivot: Swap pivot to its final position at
i + 1 - Return: The pivot’s final index
i + 1
The QuickSort Function
- Base case: If
low >= high, the subarray has 0 or 1 element (already sorted) - Partition: Call
partition()to get the pivot’s final position - Recursively sort:
- Left subarray: elements before pivot (
lowtopartIndex - 1) - Right subarray: elements after pivot (
partIndex + 1tohigh)
- Left subarray: elements before pivot (
Step-by-Step Example
For the array[10, 7, 8, 9, 1, 5]:
Initial Call: QuickSort(nums, 0, 5)
First Partition (pivot = 5):
- Scan: 1 is ≤ 5, move to left
- Result:
[1, 7, 8, 9, 10, 5]→ swap pivot →[1, 5, 8, 9, 10, 7] - Pivot 5 is now at index 1
- Left:
QuickSort(nums, 0, 0)→[1]already sorted - Right:
QuickSort(nums, 2, 5)→ Sort[8, 9, 10, 7]
- Result:
[1, 5, 7, 9, 10, 8]
- Final:
[1, 5, 7, 8, 9, 10]
Watch It in Action
When running the visualiser, you’ll see:- Green highlight (highlight2): The boundary pointer
i(marks the end of elements ≤ pivot) - Blue highlight (highlight3): The current element
jbeing examined - No red highlight: The implementation doesn’t use highlight1 in the partition function
The visualization highlights show the partition boundary (green) and the current element being examined (blue) at lines 143 and 147. Watch how elements smaller than the pivot get swapped to the left side.
Pivot Selection
This implementation uses last element as pivot (nums[high]). This is simple but has drawbacks:
- Best case: Pivot splits array roughly in half each time → O(n log n)
- Worst case: Array already sorted or reverse sorted → pivot is always smallest/largest → O(n²)
Alternative Pivot Strategies:
- First element: Same simplicity, same worst-case issue
- Random element: Reduces chance of worst case
- Median-of-three: Choose median of first, middle, and last elements
- Median-of-medians: Guarantees good pivot but adds overhead
Best Use Cases
- Large datasets: Excellent average-case performance
- General-purpose sorting: Good default choice for most applications
- In-memory sorting: Works well when data fits in memory
- When average case matters more: O(n log n) on average
Advantages
✓ Fast average-case performance: O(n log n) ✓ In-place sorting (only O(log n) stack space) ✓ Cache-friendly (good locality of reference) ✓ Practical and widely used ✓ Easy to parallelizeDisadvantages
✗ Worst-case O(n²) time with poor pivot selection ✗ Not stable (equal elements may be reordered) ✗ Recursive - can cause stack overflow for large datasets ✗ Performance depends on pivot selection strategyOptimizations
Common improvements to Quick Sort:- Randomized pivot: Reduces worst-case probability
- Three-way partitioning: Efficient for arrays with many duplicates
- Insertion sort for small subarrays: Switch to Insertion Sort when subarray size < 10-20
- Tail recursion elimination: Reduce stack space usage
- Iterative implementation: Use explicit stack to avoid recursion overhead
Quick Sort is the algorithm of choice for many standard library implementations (like C++‘s
std::sort uses a hybrid approach called “Introsort” that combines Quick Sort, Heap Sort, and Insertion Sort).