Quick Sorting
Pattern: Basic sorts
Pick a pivot, move smaller values to its left and bigger values to its right, then sort each side the same way.
The problem
You are given an array of between 1 and 1500 whole numbers. Sort it in increasing order using quick sort, and return it.
For example, [4, 1, 3, 2] becomes [1, 2, 3, 4].
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name quickSort and the limits are this guide's own. This guide uses the middle element as the pivot and a
partition that moves two indexes towards each other, which stays fast on sorted input and on many equal values.
Think first
- Choose a pivot value. If every smaller value were on its left and every bigger value on its right, what would be left to do?
- How can two indexes, one from each end, find values that are on the wrong side?
- What goes wrong if the pivot is always the first element and the array is already sorted?
Hints
Brute force, and why it fails
The simple sorts are O(n²). Merge sort is O(n log n) but needs an extra O(n) array for merging. Quick sort sorts inside the array with only the recursion stack. It is O(n log n) on average and very fast in practice, with an O(n²) worst case if the pivots keep splitting very unevenly.
The key insight
After one partition, nothing ever needs to cross the boundary again: every left value is no bigger than every right value. So the two sides are independent, smaller sorting problems.
Dry run
| pivot | 1 |
|---|
nums = [4, 1, 3, 2]. The middle index is (0 + 3) / 2 = 1, so the pivot is nums[1] = 1. i starts at the left end and j at the right end.
The plan
function sort(nums, low, high):
if low >= high:
return
pivot = nums[low + (high - low) div 2]
i = low, j = high
while i <= j:
while nums[i] < pivot: i = i + 1
while nums[j] > pivot: j = j - 1
if i <= j:
swap nums[i] and nums[j]
i = i + 1, j = j - 1
sort(nums, low, j) # values <= pivot
sort(nums, i, high) # values >= pivot
Complexity
- Time
O(n log n) average- Space
O(log n) average
Each level of partitioning does O(n) work. With reasonable pivots there are about log₂ n levels. The worst case is O(n²) time and O(n) stack, when every pivot is an extreme value. The middle pivot avoids that on sorted and reversed input.
Edge cases
- One element: the base case returns.
- Already sorted or reversed: the middle pivot splits them evenly.
- All values equal:
iandjstop at every element and swap, so the split is still even and the sort stays fast. - Quick sort is not stable: equal values can change order.
I've built my logic, show the code
Java
class Solution {
public int[] quickSort(int[] nums) {
sort(nums, 0, nums.length - 1);
return nums;
}
private void sort(int[] nums, int low, int high) {
if (low >= high) {
return;
}
int pivot = nums[low + (high - low) / 2];
int i = low;
int j = high;
while (i <= j) {
while (nums[i] < pivot) {
i++; // already on the correct (small) side
}
while (nums[j] > pivot) {
j--; // already on the correct (big) side
}
if (i <= j) { // both are on the wrong side: swap them
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
i++;
j--;
}
}
sort(nums, low, j); // everything here is <= pivot
sort(nums, i, high); // everything here is >= pivot
}
}C++
class Solution {
public:
vector<int> quickSort(vector<int>& nums) {
sort(nums, 0, static_cast<int>(nums.size()) - 1);
return nums;
}
void sort(vector<int>& nums, int low, int high) {
if (low >= high) {
return;
}
int pivot = nums[low + (high - low) / 2];
int i = low;
int j = high;
while (i <= j) {
while (nums[i] < pivot) {
i++; // already on the correct (small) side
}
while (nums[j] > pivot) {
j--; // already on the correct (big) side
}
if (i <= j) { // both are on the wrong side: swap them
swap(nums[i], nums[j]);
i++;
j--;
}
}
sort(nums, low, j); // everything here is <= pivot
sort(nums, i, high); // everything here is >= pivot
}
};Python
class Solution:
def quickSort(self, nums):
self.sort(nums, 0, len(nums) - 1)
return nums
def sort(self, nums, low, high):
if low >= high:
return
pivot = nums[(low + high) // 2]
i, j = low, high
while i <= j:
while nums[i] < pivot:
i += 1 # already on the correct (small) side
while nums[j] > pivot:
j -= 1 # already on the correct (big) side
if i <= j: # both are on the wrong side: swap them
nums[i], nums[j] = nums[j], nums[i]
i += 1
j -= 1
self.sort(nums, low, j) # everything here is <= pivot
self.sort(nums, i, high) # everything here is >= pivotCommon mistakes
- Using
<=and>=in the inner scans, which letsiorjrun past the end of the part. - Recursing on
(low, i)and(j, high), which overlaps the sections and can loop forever. - Always picking the first or last element as the pivot, which is O(n²) on sorted input and can overflow the stack.