Partitioning and Sorting Arrays with Many Repeated Entries
Pattern: Dutch national flag
Quicksort with a three-way partition. Each round splits the range into less than, equal to and greater than the pivot, and every copy of the pivot is finished at once.
The problem
Sort an array of whole numbers in increasing order, in place, when it may contain many repeated values. For example,
[4, 9, 4, 4, 1, 9, 4] becomes [1, 4, 4, 4, 4, 9, 9]. The aim is a quicksort that stays fast however many repeats
there are.
The link above is a Baeldung article on this topic. The function name sortArray is this guide's own. Write the sort
yourself, without a library sort.
Think first
- Plain quicksort splits a range into "at most the pivot" and "more than the pivot". What happens when every value is the same?
- With three groups (less, equal, greater), which group never needs sorting again?
- Which earlier problem in this pattern does one partition step look like?
Hints
Brute force, and why it fails
Plain two-way quicksort is O(n log n) on average but O(n²) on arrays of many equal values. Merge sort is always O(n log n) but needs O(n) extra memory. Three-way quicksort keeps the in-place speed and handles repeats.
The key insight
Every copy of the pivot is placed in one partition and then left alone. With few distinct values, the recursion stops after about as many levels as there are distinct values.
Dry run
| pivot | 4 |
|---|
a = [4, 9, 4, 4, 1, 9, 4]. The pivot is the middle value, a[3] = 4. lt and i start at 0, and gt at 6.
The plan
function sort(a, lo, hi):
if lo >= hi: return
pivot = a[lo + (hi - lo) / 2]
lt = lo, i = lo, gt = hi
while i <= gt:
if a[i] < pivot: swap a[lt], a[i]; lt = lt + 1; i = i + 1
else if a[i] > pivot: swap a[i], a[gt]; gt = gt - 1
else: i = i + 1
sort(a, lo, lt - 1)
sort(a, gt + 1, hi)
Complexity
- Time
O(n log n) on average- Space
O(log n) on average
Each level of recursion does O(n) partition work. With a middle pivot the depth is about log n on typical input. With
only d distinct values, it is at most d levels, so many repeats make it faster, not slower. The space is the
recursion stack.
Edge cases
- Empty array or one element: nothing to do.
- All equal: one partition finishes everything.
- Two elements in the wrong order: one partition swaps them.
I've built my logic, show the code
Java
class Solution {
public void sortArray(int[] a) {
sort(a, 0, a.length - 1);
}
private void sort(int[] a, int lo, int hi) {
if (lo >= hi) return;
int pivot = a[lo + (hi - lo) / 2];
int lt = lo, i = lo, gt = hi; // a[lo..lt-1] < pivot, a[lt..i-1] == pivot, a[gt+1..hi] > pivot
while (i <= gt) {
if (a[i] < pivot) {
swap(a, lt++, i++);
} else if (a[i] > pivot) {
swap(a, i, gt--);
} else {
i++;
}
}
sort(a, lo, lt - 1); // the pivot copies in a[lt..gt] are already in place
sort(a, gt + 1, hi);
}
private void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}C++
class Solution {
public:
void sortArray(vector<int>& a) {
sortRange(a, 0, static_cast<int>(a.size()) - 1);
}
void sortRange(vector<int>& a, int lo, int hi) {
if (lo >= hi) return;
int pivot = a[lo + (hi - lo) / 2];
int lt = lo, i = lo, gt = hi; // a[lo..lt-1] < pivot, a[lt..i-1] == pivot, a[gt+1..hi] > pivot
while (i <= gt) {
if (a[i] < pivot) {
swap(a[lt++], a[i++]);
} else if (a[i] > pivot) {
swap(a[i], a[gt--]);
} else {
i++;
}
}
sortRange(a, lo, lt - 1); // the pivot copies in a[lt..gt] are already in place
sortRange(a, gt + 1, hi);
}
};Python
class Solution:
def sortArray(self, a: list[int]) -> None:
self.sort_range(a, 0, len(a) - 1)
def sort_range(self, a: list[int], lo: int, hi: int) -> None:
if lo >= hi:
return
pivot = a[lo + (hi - lo) // 2]
lt, i, gt = lo, lo, hi # a[lo:lt] < pivot, a[lt:i] == pivot, a[gt+1:hi+1] > pivot
while i <= gt:
if a[i] < pivot:
a[lt], a[i] = a[i], a[lt]
lt += 1
i += 1
elif a[i] > pivot:
a[i], a[gt] = a[gt], a[i]
gt -= 1
else:
i += 1
self.sort_range(a, lo, lt - 1) # the pivot copies in a[lt:gt+1] are already in place
self.sort_range(a, gt + 1, hi)Common mistakes
- Recursing on
lo..ltorgt..hi, which includes pivot copies again and can recurse forever. - Moving
iafter swapping withgt. - Always picking the first element as pivot, which makes sorted input slow (O(n²)) and recursion very deep.