š Quick Sort Algorithm Explained
Quick Sort is a divide-and-conquer algorithm that efficiently sorts an array by selecting a pivot element and partitioning the other elements into two groups:
- Smaller than the pivot
- Greater than the pivot
This process is recursively applied to both groups until the entire array is sorted.
š Steps of Quick Sort
- Choose a Pivot: Pick an element from the array (commonly the last, first, or a random element).
- Partitioning: Rearrange the array so that elements smaller than the pivot come before it, and elements greater come after.
- Recursion: Apply Quick Sort on the left and right sub-arrays.
- Base Case: When the sub-array has 0 or 1 element, it's already sorted.
Quick Sort: Time Complexity & Key Takeaways
Time Complexity Table
Scenario | Time Complexity | Description |
---|
Best Case | O(n log n) | Occurs when the pivot divides the array into two nearly equal parts. |
Average Case | O(n log n) | Typically achieved with balanced partitions during recursion. |
Worst Case | O(n²) | Happens when the pivot is the smallest or largest element each time, leading to highly unbalanced partitions (e.g., already sorted array). |
Key Takeaways
- Divide and Conquer: Quick Sort works by breaking the problem into smaller sub-problems using a pivot to partition the array.
- Efficiency: It generally performs very well with an average-case time complexity of O(n log n), making it suitable for large datasets.
- Worst Case Pitfall: Poor pivot selection (e.g., always picking the smallest or largest element) can degrade its performance to O(n²).
- In-Place Sorting: Quick Sort can be implemented in-place, requiring little additional memory.
- Not Stable: The algorithm does not maintain the relative order of equal elements.
Quick Sort remains a popular choice due to its average-case efficiency, despite potential pitfalls with worst-case performance.