Quick Sort
Algorithms
Quick sort is a divide-and-conquer algorithm that picks a pivot element and partitions the array around the pivot, placing smaller elements before it and larger elements after it.
Algorithm
The quick sort algorithm follows these steps:
- Pick a pivot element from the array
- Partition the array: elements less than pivot go left, elements greater go right
- Recursively apply quick sort to the left and right partitions
Time Complexity
- Best case:
- Average case:
- Worst case: (when pivot is always the smallest or largest element)
Implementation
def quick_sort(arr):
if len(arr) <= 1:
return arr
else:
# Choose a pivot element
pivot = arr[len(arr) // 2]
# Partitioning step
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
# Recursively apply quick_sort to the partitions
return quick_sort(left) + middle + quick_sort(right)
# Example usage with different numbers
arr = [45, 23, 78, 12, 56, 89, 34]
sorted_arr = quick_sort(arr)
print("Sorted array:", sorted_arr) Trace it by hand
Lomuto scans j from left to right, maintaining a "small index" i = position of the last known ≤-pivot element. When arr[j] ≤ pivot, increment i and swap arr[i] with arr[j].
| j | arr[j] | action | array after |
|---|---|---|---|
| 0 | 3 | ≤5, i=0, swap arr[0]↔arr[0] | [3, 6, 1, 8, 2, 9, 4, 7, 5] |
| 1 | 6 | >5, skip | [3, 6, 1, 8, 2, 9, 4, 7, 5] |
| 2 | 1 | ≤5, i=1, swap arr[1]↔arr[2] | [3, 1, 6, 8, 2, 9, 4, 7, 5] |
| 3 | 8 | >5, skip | [3, 1, 6, 8, 2, 9, 4, 7, 5] |
| 4 | 2 | ≤5, i=2, swap arr[2]↔arr[4] | [3, 1, 2, 8, 6, 9, 4, 7, 5] |
| 5 | 9 | >5, skip | [3, 1, 2, 8, 6, 9, 4, 7, 5] |
| 6 | 4 | ≤5, i=3, swap arr[3]↔arr[6] | [3, 1, 2, 4, 6, 9, 8, 7, 5] |
| 7 | 7 | >5, skip | [3, 1, 2, 4, 6, 9, 8, 7, 5] |
End of loop, swap arr[i+1] = arr[4] with the pivot arr[8]:
[3, 1, 2, 4, 5, 9, 8, 7, 6]. Pivot index: 4.
The left side [3, 1, 2, 4] is ≤5, the right side [9, 8, 7, 6] is >5. Both halves are unsorted internally — that's what the recursive calls handle. Quick sort's worst case (when the pivot is always extreme) gives ; randomized pivot selection gives expected .