Quick Sort
Speed
Pseudocode
1quickSort(a, lo, hi):2 if lo < hi:3 pivot ← a[hi]; i ← lo4 for j ← lo to hi − 1:5 if a[j] < pivot:6 swap a[i], a[j]; i ← i + 17 swap a[i], a[hi] // pivot lands in place8 quickSort(a, lo, i − 1); quickSort(a, i + 1, hi)
Comparisons
0
Swaps
0
Partitions
0
pivotvalue we split aroundiend of the “smaller” sidein its final place
How Quick Sort Works
Quick Sort is a highly efficient divide-and-conquer algorithm that works by selecting a 'pivot' element and partitioning the array around it. Elements smaller than the pivot go to the left, larger elements go to the right.
The algorithm follows these key steps:
- Choose Pivot: Select an element as the pivot (often the last element)
- Partition: Rearrange array so elements < pivot are before it, elements > pivot are after
- Recursion: Apply quick sort to the sub-arrays on both sides of the pivot
- Base Case: Single elements or empty arrays are already sorted
Implementation
Performance Analysis
Time Complexity
- • Best: O(n log n) - balanced partitions
- • Average: O(n log n)
- • Worst: O(n²) - already sorted with bad pivot
- • Recurrence: T(n) = T(k) + T(n-k-1) + O(n)
Space & Properties
- • Space: O(log n) recursion stack
- • Not stable: relative order not preserved
- • In-place: sorts within original array
- • Cache-friendly: good locality of reference
Pivot Selection Strategies
- • First/Last element: Simple but can be O(n²)
- • Random pivot: Avoids worst case on sorted data
- • Median-of-three: Better performance, less variance
- • Median-of-medians: Guarantees O(n log n) but complex
Why Quick Sort is Popular
- • Fast in practice: Low constant factors
- • Cache efficient: Good memory access patterns
- • In-place sorting: Minimal extra memory
- • Widely implemented: Standard library choice