Quick Sort
Quick Sort uses divide-and-conquer: pick a pivot, partition into “less than pivot” and “greater than pivot,” then recursively sort both sides.
Click "Step forward" to watch the algorithm state change.
- Choose a pivot (e.g., first element).
- Partition: elements smaller than the pivot go left, larger ones go right.
- Recursively quick-sort left and right.
Pseudo-code:
function quickSort(A, low, high):
if low < high:
pivot = partition(A, low, high)
quickSort(A, low, pivot-1)
quickSort(A, pivot+1, high)
function partition(A, low, high):
pivot = A[low]
i = low
j = high
while i < j:
while i < j and A[j] >= pivot:
j--
A[i] = A[j]
while i < j and A[i] <= pivot:
i++
A[j] = A[i]
A[i] = pivot
return i
int Partition(int A[], int low, int high) {
int pivot = A[low]; // take the first element as the pivot
while (low < high) {
while (low < high && A[high] >= pivot) high--;
A[low] = A[high]; // move the elements smaller than the pivot to the left
while (low < high && A[low] <= pivot) low++;
A[high] = A[low]; // move the elements greater than the pivot to the right
}
A[low] = pivot; // the pivot settles into its final position
return low; // return the position of the pivot
}
void QuickSort(int A[], int low, int high) {
if (low < high) {
int pivot = Partition(A, low, high);
QuickSort(A, low, pivot - 1); // the left half
QuickSort(A, pivot + 1, high); // the right half
}
}
Choosing the Pivot
- Random choice: pick a random element as the pivot, which avoids the worst case
- Median of three: take the median of the first, the middle, and the last element as the pivot, which lowers the probability of degrading to
- Best/avg:
- Worst: (highly unbalanced partitions)
- Space: (recursion stack)
- Stability: unstable
Exercise 1
Run quick sort on ; show the first partition result.
Approach: Use the first element as the pivot and partition the array around it.
Steps:
- Use as the pivot; smaller values on the left, larger values on the right
- After one partition: [5, 1, 2, 3, 4, 6, 7, 9, 10, 8]
Answer: As shown above; the values left of are smaller and the values right of it are larger.
Exercise 2
What are quick sort’s time and space complexities?
Approach: Consider the time complexity and the extra space.
Steps:
- Time complexity (average), (worst case)
- Space complexity
Answer: Time ~, space .
