Speed:
Quick Sort
Average: O(n log n)Worst: O(n²)Space: O(log n)
⚡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