Quick Sort with Pivot Selection
Quick Sort is a divide-and-conquer sorting algorithm that picks a pivot element and partitions the array so that elements smaller than the pivot come before it and elements larger come after. The choice of pivot heavily influences the algorithm's real-world performance.
Common Pivot Selection Strategies
- First element: simple, but leads to O(n²) on already sorted arrays.
- Last element: the classic Lomuto partition scheme.
- Random element: reduces the chance of worst-case behavior on adversarial input.
- Median-of-three: picks the median of the first, middle, and last elements for a more balanced split.
import random
def quick_sort(arr, low=0, high=None):
if high is None:
high = len(arr) - 1
if low < high:
pivot_index = partition(arr, low, high)
quick_sort(arr, low, pivot_index - 1)
quick_sort(arr, pivot_index + 1, high)
return arr
def partition(arr, low, high):
rand = random.randint(low, high)
arr[rand], arr[high] = arr[high], arr[rand] # random pivot
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
Complexity
| Case | Time | Space |
|---|---|---|
| Best | O(n log n) | O(log n) |
| Average | O(n log n) | O(log n) |
| Worst (poor pivot) | O(n²) | O(n) |
Why Pivot Choice Matters
A poor pivot (e.g. always picking the first element on a sorted array) creates highly unbalanced partitions, degrading performance to O(n²). Random or median-of-three pivot selection keeps partitions balanced on average, preserving the O(n log n) behavior in practice.
Ready to master Data Structures & Algorithms?
Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.
.png)