You are given a list of numbers. Write a function to find the "median of medians". Please what is the median of medians algorithm used for? (As a pivot selection strategy for a selection algorithm like Quickselect), describe the steps of the median of medians algorithm, what is the significance of this algorithm in terms of the worst-case performance of Quickselect, and write the code to implement this algorithm.
Assistant
We are going to explain the median of medians algorithm and its use, then present the code.
The median of medians algorithm is used as a pivot selection strategy in selection algorithms (like Quickselect) to guarantee a good pivot that leads to a worst-case linear time complexity.
Steps of the median of medians algorithm (for an array A of n elements and selecting the k-th smallest element):
If n is small (say, less than or equal to 5), sort the array and return the k-th element.
Divide the array into groups of 5 (or fewer in the last group). For each group, sort it (using insertion sort for small arrays) and find its median.
Recursively find the median of these medians (let's call it M). This M is used as the pivot.
Partition the array around M. Let pivot_index be the index of M after partitioning.
Compare k with pivot_index:
a. If k == pivot_index, return M.
b. If k < pivot_index, recursively select in the left part (from low to pivot_index-1).
c. If k > pivot_index, recursively select in the right part (from pivot_index+1 to high), adjusting k accordingly.
Significance:
The median of medians algorithm guarantees that the pivot is good enough to split the array into two parts, each of which has at least a constant fraction (at least 3n/10) of the elements. This ensures that the worst-case time complexity of Quickselect with this pivot selection is O(n).
However, note that the constant factor in the worst-case linear time is higher than the average-case of Quickselect with a random pivot, so in practice random pivot selection is often used.
Code implementation:
We'll write a function select that takes an array arr, a low index, a high index, and an integer k (0-indexed) and returns the k-th smallest element in the subarray arr[low..high].
Steps in code:
If high - low + 1 <= 5, sort the subarray and return the k-th element.
Otherwise, divide the subarray into groups of 5. For each group, find the median and collect these medians in a list.
Recursively find the median of the medians list (i.e., the median at index (len(medians)//2) if we want the lower median).
Partition the subarray around this median of medians.
Let pivot_index be the index of the median of medians after partitioning.
Compare k with pivot_index and recurse accordingly.
Note: When partitioning, we must handle duplicates properly. We'll use the standard Lomuto partition scheme or Hoare's partition. However, note that in the median of medians algorithm, we are using the median of medians as the pivot, so we must find its index after partitioning. We can do:
Find the index of the pivot (median of medians) in the original array. But note: the pivot might appear multiple times? The median of medians is one of the elements, but in the array there might be duplicates.
Alternatively, we can partition in a way that returns the index of the pivot. We can do:
Option 1: Use a partition function that returns the index of the pivot after partitioning.
We'll write a helper partition function that partitions the array around a given pivot value and returns the index of the pivot (if there are duplicates, we can return the first occurrence or any occurrence? We need to be consistent).
However, note that the pivot we are using is one of the medians, and it must be in the array. So we can:
Step 4: Partition the array around the median of medians (let's call it pivot_value). We want to partition such that all elements < pivot_value are on the left, equal in the middle, and > on the right. But then we need to know the exact position of one occurrence of the pivot.
Alternatively, we can do:
We can use the standard Lomuto partition that uses the last element as the pivot, but we want to use our pivot. So we can:
Swap the pivot to the last position and then run Lomuto partition, but then the pivot will be placed at its correct position and we return that index.
However, note that the pivot might not be unique. The Lomuto partition will put the last element (which we set as the pivot) in its correct position and return that index. But if there are duplicates, the pivot might appear multiple times and the Lomuto partition will put the last occurrence? Actually, Lomuto partition typically returns the index of the last element that was placed as the pivot. But note:
In the Lomuto partition, we have:
code
pivot = arr[high]
i = low - 1
for j from low to high-1:
if arr[j] <= pivot:
i++
swap arr[i] and arr[j]
swap arr[i+1] and arr[high]
return i+1
So it returns the index of the pivot (which was at high originally) and after the swap, the pivot is at index i+1.
But in our case, we want to partition around pivot_value and we have to choose one occurrence of that value to be the pivot. We can:
Find an index of an element equal to pivot_value and swap it to the end, then run Lomuto.
However, note: the median of medians might not be present in the current subarray? Actually, it must be because we took the median of the medians of the groups, and each median is an element of the array. So the median of medians is one of the elements of the array.
So steps:
code
a. Find an index `pivot_index_original` in the current subarray such that arr[pivot_index_original] == pivot_value. We can just search linearly (since we know it's there).
b. Swap arr[pivot_index_original] with arr[high] (so that the pivot is at the end).
c. Run Lomuto partition on the subarray from low to high. This will put the pivot (which is at `high`) in its correct position and return that index.
Then we have:
code
Let `pivot_index` be the returned index from partition.
Then compare k with pivot_index.
Recurse accordingly.
However, note that the above linear search for the pivot value in the subarray might break the overall linear time? Actually, we are already doing a linear time partition, and the linear search for the pivot is O(n) too, but note that we are only searching in the current subarray. But the total work in the recursive calls is still linear because the partition step is O(n) and we are doing a linear search for the pivot. But wait, we are already doing a partition that requires scanning the array. So we can actually combine:
Alternatively, we can do:
In the partition step, we can:
code
Let `pivot_value` be the median of medians.
We want to partition the array around `pivot_value` and also return the index of one occurrence of `pivot_value` that ends up in the correct position.
But note: the Lomuto partition as described above will put the last element (which we set to be an occurrence of pivot_value) in the correct position. So we can:
code
Step 1: Find an index `idx` in [low, high] such that arr[idx] == pivot_value. (We can do a linear scan, but note that we are going to do a partition anyway, so we can do the scan and then swap that element to the end.)
Step 2: Swap arr[idx] with arr[high].
Step 3: Run the standard Lomuto partition (with the pivot at `high`).
Then the pivot will be placed at index `i+1` and we return `i+1`.
This is acceptable because the linear scan is O(n) and the partition is O(n), so together O(n). But note that we are already doing a linear scan in the partition loop. So we are doing two passes? Actually, the linear scan for the pivot is one pass, and then the partition loop is another pass. But we can combine them? We can do:
code
We can do the partition without swapping the pivot to the end? But then we have to handle the pivot separately.
Alternatively, we can use a three-way partition (Dutch national flag) that partitions the array into three parts: less than, equal to, and greater than the pivot. Then we can return the range of the pivot. But then we have to adjust k accordingly.
However, the standard median of medians algorithm uses a two-way partition (with the pivot placed at its correct position). So we'll stick to the two-way partition.
But note: the two-way partition (Lomuto) with duplicates will put all elements equal to the pivot in the left part? Actually, the condition is arr[j] <= pivot, so duplicates of the pivot will be swapped to the left. Then at the end, we swap the pivot (from the end) to the position after the last element that is <= pivot. So the pivot will be placed at the first position of the elements that are > pivot? Actually, after the loop, all elements from low to i are <= pivot, and from i+1 to high-1 are > pivot. Then we swap the pivot (at high) with arr[i+1]. So now:
So the pivot is at index i+1 and all elements equal to the pivot (except the one we swapped from the end) are in the left part (<=). This means that if there are duplicates, they will be scattered: some in the left part and one at the pivot position. But that's okay because we are only interested in the position of the pivot we chose.
But note: the k-th smallest element might be one of the duplicates. However, if k is in the range [i+1, i+count] where count is the number of duplicates? Actually, the partition we did does not group duplicates together. So if we have duplicates, we might have:
code
Example: [1,2,2,2,3] with pivot=2. After partition (using Lomuto with pivot at the end):
We set the last element (3) to be the pivot? No, we set an occurrence of 2 to be at the end. So let's say we set the last 2 to be at the end? Actually, we have to find an occurrence of 2 and swap it to the end.
Suppose the array is [1,2,2,2,3] and we choose the first 2 (index 1) as the pivot. Then we swap index 1 with index 4 (the last element), so we get [1,3,2,2,2]. Now we run Lomuto with pivot=2 (which is at index 4). Then:
j from 0 to 3:
j=0: 1<=2 -> i=0, swap arr[0] with arr[0] -> [1,3,2,2,2]
j=1: 3<=2? no.
j=2: 2<=2 -> i=1, swap arr[1] and arr[2] -> [1,2,3,2,2]
j=3: 2<=2 -> i=2, swap arr[2] and arr[3] -> [1,2,2,3,2]
Then swap arr[i+1] (index 3) with arr[4] -> [1,2,2,2,3]
So the pivot (2) is now at index 3? But wait, we started with the array [1,2,2,2,3] and after partition we have [1,2,2,2,3]. The pivot (which was the 2 at index 4 originally) is now at index 3? Actually, after the last swap, the pivot (which was at index 4) is swapped to index i+1 (which is 3). So the array becomes [1,2,2,2,3] and the pivot is at index 3.
But note: the array is now partitioned such that:
elements at indices 0,1,2 are <=2, and elements at indices 3,4 are >=2? Actually, index 3 is the pivot (2) and index 4 is 3 which is >2.
So the pivot is at index 3. The duplicates of 2 are at indices 1,2,3. So they are not all on the left of the pivot. But note that the pivot we used is one of the 2's, and it is placed at index 3. The other 2's are at indices 1 and 2, which are <=2 and are in the left part.
This means that if we are looking for the 3rd smallest element (k=2, 0-indexed) then we would look in the left part (0..2) because k (2) < pivot_index (3). And indeed, the 3rd smallest is the element at index 2 in the original sorted array? Actually, the sorted array is [1,2,2,2,3]. The 3rd smallest (0-indexed k=2) is 2. And in the partitioned array, the left part (0..2) is [1,2,2] and the 2 at index 2 is indeed the 3rd smallest.
But note: if k were 3 (the 4th smallest) then we would compare k (3) with pivot_index (3) and return the pivot (which is 2). That is correct because the 4th smallest is also 2.
So the two-way partition with duplicates works because we are using one occurrence of the pivot as the pivot and the other duplicates are in the left part (because they are <= pivot). But note: in the example, the left part has two 2's and the pivot is also 2. So the left part has two 2's and the pivot is the third 2. This is acceptable because the k-th smallest might be any of the duplicates.
However, the algorithm does not guarantee that all duplicates are on one side. But that's okay because we are recursing on the side that contains the k-th element.
But wait: what if the k-th element is a duplicate and it is in the right part? In the example, if k=4 (the 5th smallest) then we would look in the right part (indices 4..4) and get 3, which is correct.
So the two-way partition works.
8. However, note that the median of medians algorithm is designed to guarantee that the pivot is a good pivot. The analysis shows that at least 3n/10 elements are less than or equal to the pivot and at least 3n/10 are greater than or equal to the pivot. But note: the duplicates might break this guarantee? Actually, the guarantee is for the pivot we choose (which is the median of medians). The duplicates of the pivot are counted in the set of elements <= pivot and also in the set of elements >= pivot. But the guarantee is about the number of elements that are strictly less and strictly greater? The standard analysis says:
code
Let n be the number of elements in the current subarray.
We divide into groups of 5 (except possibly the last). There are ceil(n/5) groups.
The median of medians is the median of the medians of these groups.
At least half of the group medians are less than or equal to the median of medians.
Each of these medians (that are <= the pivot) has at least 3 elements (in its group of 5) that are <= the median (and hence <= the pivot) because in a group of 5, the median has 2 elements less than or equal to it (including itself) and 2 greater. Actually, wait: in a group of 5 sorted: [a,b,c,d,e] with c being the median. Then there are 3 elements (a,b,c) that are <= c. But note: the median of medians is the median of the medians. So if the median of medians is M, then at least ceil(ceil(n/5)/2) groups have their median <= M. And in each such group, there are at least 3 elements (including the median) that are <= M. So the total number of elements <= M is at least 3 * ceil(ceil(n/5)/2). This is at least 3n/10 (for n>=5). Similarly for the greater side.
But note: the above count includes the pivot itself and possibly other duplicates? Actually, the count is for elements <= M. If there are duplicates of M, then they are included in this count. So the guarantee is that at least 3n/10 elements are <= M and at least 3n/10 are >= M.
So the two-way partition is acceptable.
Implementation:
We'll write:
def select(arr, low, high, k):
# k is 0-indexed
code
# If the subarray has 5 or fewer elements, sort and return the k-th.
if high - low + 1 <= 5:
sub = arr[low:high+1]
sub.sort()
return sub[k]
# Step 1: Divide into groups of 5 and find the median of each group.
medians = []
for i in range(low, high+1, 5):
group_end = min(i+4, high)
group = arr[i:group_end+1]
group.sort()
median = group[len(group)//2] # lower median for even length
medians.append(median)
# Step 2: Find the median of medians recursively.
num_medians = len(medians)
if num_medians <= 5:
medians.sort()
pivot_value = medians[num_medians//2]
else:
pivot_value = select(medians, 0, num_medians-1, num_medians//2)
# Step 3: Partition the array around pivot_value and get the index of the pivot.
# We need to find an index in [low, high] where arr[idx] == pivot_value and swap it to the end.
pivot_index = -1
for i in range(low, high+1):
if arr[i] == pivot_value:
pivot_index = i
break
# Swap the pivot to the end.
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
# Now run Lomuto partition.
i = low - 1
for j in range(low, high):
if arr[j] <= pivot_value:
i += 1
arr[i], arr[j] = arr[j], arr[i]
# Place the pivot in the correct position.
arr[i+1], arr[high] = arr[high], arr[i+1]
pivot_index = i+1
# Now pivot_index is the index of the pivot (one occurrence) after partition.
if k == pivot_index:
return arr[pivot_index]
elif k < pivot_index:
return select(arr, low, pivot_index-1, k)
else:
return select(arr, pivot_index+1, high, k)
However, note: the above code modifies the array in place. We are swapping elements. This is acceptable for Quickselect because we are only interested in the k-th element and we don't care about the order of the rest.
But note: the median of medians algorithm is used to choose a good pivot, and then we partition. The above code does that.
However, there is a potential issue: when we find the pivot_value, we are searching for an element equal to pivot_value. But what if the pivot_value appears multiple times? We take the first occurrence. That's okay because we only need one occurrence to be the pivot.
But note: the pivot_value might not be in the current subarray? It must be because it is the median of medians of groups of this subarray, and each median is an element of the subarray. So it is in the subarray.
Another issue: when we partition, we use <= so that elements equal to the pivot go to the left. This is consistent with the analysis.
But note: the analysis of the median of medians assumes that the pivot is chosen as the median of medians, which is one of the elements. The partition step then places that element in its correct position.
However, the above code for the median of medians step (when the number of medians is more than 5) uses the same select function recursively. But note: the select function we are writing is for the original array? No, for the medians array. So we are recursively calling select on the medians array. This is correct.
But wait: in the recursive call for the medians, we are passing medians as the array and 0 and num_medians-1 as the bounds, and num_medians//2 as the k. This is to find the median of the medians.
However, note that the medians array might have duplicates? Yes, but that's okay.
Let's test with a simple example:
arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
Groups: [1,2,3,4,5] -> median 3
[6,7,8,9,10] -> median 8
[11,12,13,14,15] -> median 13
medians = [3,8,13]
median of medians: 8 (the middle one)
Then we partition around 8.
But note: the algorithm is designed for any k. Let's say k=7 (the 8th smallest, 0-indexed 7). We expect 8.
Steps:
code
pivot_value = 8.
Find an index of 8 (say index 7? Actually, in the original array, 8 is at index 7 (0-indexed). Then we swap it to the end (index 14). Then partition:
We run the loop from 0 to 13. All elements <=8 will be swapped to the left. Then at the end, we swap the pivot (which is at index 14) with arr[i+1]. The pivot will be placed at the position after the last element that is <=8.
How many elements are <=8? 8 (1,2,3,4,5,6,7,8). So after partition, the pivot (8) will be at index 7? Let's see:
Initially: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] and we swap 8 (index7) with 15 (index14) -> [1,2,3,4,5,6,7,15,9,10,11,12,13,14,8]
Then we run the loop from 0 to 13 (j=0..13). We are partitioning around 8.
j=0:1<=8 -> i=0, swap arr[0] with arr[0] -> [1,2,3,4,5,6,7,15,9,10,11,12,13,14,8]
j=1:2<=8 -> i=1, swap arr[1] with arr[1] -> same
j=2:3<=8 -> i=2
j=3:4<=8 -> i=3
j=4:5<=8 -> i=4
j=5:6<=8 -> i=5
j=6:7<=8 -> i=6
j=7:15<=8? no.
j=8:9<=8? no.
... until j=13:14<=8? no.
Then we swap arr[i+1] (index7) with arr[14] (which is 8). So we swap 15 and 8.
Now the array becomes: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
And pivot_index = 7.
Then k=7, so we return arr[7] which is 8. Correct.
But note: the pivot we used was 8, and after partition it is at index 7. And k=7, so we return it.
If k=6, then we would recurse on the left part (0..6) and then find the 6th element in that part? But note: the left part has 7 elements (indices 0..6) and we are looking for the 6th element (0-indexed) in the entire array, which is the 6th element in the left part? Actually, the left part has 7 elements, and we are looking for the 6th (0-indexed) in the entire array, which is the element at index 6 in the entire array. But after partition, the left part (0..6) has the 7 smallest elements (1..7). The 6th index (0-indexed) in the entire array is the 7th smallest, which is 7. And in the left part, the 6th index (0-indexed) is the last element of the left part, which is 7. So we would recurse on the left part with k=6 (because we are looking for the 6th element in the entire array, and the left part has 7 elements, so we look for the 6th in the left part? Actually, note:
code
We have:
left part: indices 0..6 (7 elements)
pivot at index 7
right part: indices 8..14 (7 elements)
k=6 is less than pivot_index=7, so we recurse on the left part with the same k (because the left part's indices are 0..6, and we are looking for the 6th element in the entire array, which is the 6th element in the left part? Wait, the entire array's indices are 0..14. The left part has indices 0..6, so the element that was originally at index 6 in the entire array is now at index 6 in the left part? Actually, after partition, the elements in the left part are the 7 smallest, so the element that was originally at index 6 (which is 7) is now at index 6 in the left part? Yes, because the left part is exactly the first 7 elements. So we recurse on the left part with k=6 (the same k) because the left part starts at index 0 and we want the element that is at index 6 in the entire array, which is the 6th element in the left part.
But note: the recursive call is `select(arr, low, pivot_index-1, k)`. Here, low=0, pivot_index-1=6, and k=6. So we are looking for the 6th element (0-indexed) in the subarray from 0 to 6. That is the last element of that subarray, which is 7. Correct.
So the code seems correct.
However, note: the above code for the medians array when the number of medians is <=5 uses sorting and then takes the middle. But what if the number of medians is even? We take the lower median (len(medians)//2). This is acceptable because we only need a good pivot, not necessarily the exact median.
But note: the standard median of medians algorithm uses the median of the medians (which for an even number of medians, we can take either the lower or upper median). The analysis still holds with a slight adjustment in the constants.
Let's adjust: if we have an even number of medians, we take the lower median. Then at least half of the medians are less than or equal to the median of medians? Actually, if we have an even number, say 6 medians, then the median (the 3rd element in 0-indexed) has 3 medians less than or equal to it (the first three) and 3 greater? Actually, if we take the 3rd (0-indexed 2) then the first three (indices 0,1,2) are <= the median? But note: the median is the 3rd smallest, so there are 3 medians that are <= it (including itself) and 3 that are >=? Actually, for 6 elements, the median (3rd smallest) has 3 elements <= it and 3 >=. So the same guarantee holds.
So we are safe.
But note: the above code for the base case (when the subarray has <=5 elements) sorts the subarray and returns the k-th. This is correct.
However, note that the k in the recursive call for the medians array is num_medians//2. For example, if we have 6 medians, then we want the 3rd smallest (0-indexed 2). That is the lower median.
Implementation note: the above code does an in-place modification of the original array. This is acceptable for Quickselect because we are only interested in the k-th element.
But note: the median of medians algorithm is often described as a selection algorithm that runs in worst-case O(n). The above code does that.
However, the constant factor is high. In practice, for small arrays (like <=5) we use sorting, which is acceptable.
Let's write the code accordingly.
But note: the above code for the base case creates a subarray and sorts it. We can avoid creating a new array by sorting in place? But the subarray is small (at most 5), so it's okay.
Alternatively, we can use insertion sort for the base case to avoid the overhead of Python's sort for 5 elements? But it's not necessary.
Let's code accordingly.
However, note: the above code does a linear search for the pivot_value in the current subarray. This is O(n). But note that the partition step also does O(n). So together it's O(n). But we can avoid the extra linear search by doing:
We can modify the partition function to take the pivot value and then during the partition, we can also note the index of the pivot if we see it? But note: we are swapping the pivot to the end. So we need to know an index of the pivot to swap it to the end. We can do:
code
In the partition loop, we can also look for the pivot and remember its index? But then we are doing two things in one loop.
Alternatively, we can do:
code
We can run the partition without swapping the pivot to the end? But then we have to handle the pivot separately.
The standard way is to swap the pivot to the end and then run the standard Lomuto. So we need to find an index of the pivot. We can do:
code
We can do the linear search and then swap. That's what we did.
But note: the linear search might be avoided if we, during the creation of the groups, remember the index of the median in the original array? Actually, when we compute the medians, we are sorting groups of at most 5. We could remember the index of the median in the original array for each group. Then, when we choose the median of medians, we know the index of that median in the original array? But wait: the median of medians is computed from the medians array, which is a list of values. We don't have the index of the median of medians in the original array. We only have its value.
So we have to search for that value in the original array. But note: the median of medians might appear multiple times. We only need one occurrence.
So the linear search is necessary.
But note: the linear search is O(n) and we are already doing O(n) in the partition. So the overall time is still O(n).
However, the constant factor might be increased.
We can try to combine the linear search and the partition? We can:
code
Let pivot_value be the median of medians.
We want to partition the array and also find an occurrence of pivot_value to put at the end.
We can do:
i = low - 1
pivot_index = -1 # we will record an index of the pivot if we see it during the scan.
for j in range(low, high+1):
if arr[j] == pivot_value and pivot_index == -1:
pivot_index = j
if j != high: # we don't want to swap the pivot to the end until the end?
# But note: we are going to swap the pivot to the end at the end of the loop? Actually, we want to partition the array from low to high-1, and then swap the pivot (which we found) to the end? But then we have to exclude the pivot from the partition loop? This is getting messy.
Alternatively, we can do:
We can run the partition loop from low to high, but we treat the pivot (the element we found) specially? We want to exclude it from the partition loop and then put it in the correct position at the end.
But the standard Lomuto partition expects the pivot to be at the end. So we can:
Step 1: Find an index `p` of the pivot (any occurrence).
Step 2: Swap arr[p] with arr[high].
Step 3: Run the standard Lomuto from low to high-1.
This is what we did.
So we'll stick to that.
Edge cases: empty array, k out of bounds? We assume k is between 0 and n-1.
We can write a wrapper function to make it easier to call:
However, note that the above select function modifies the input array. If we don't want to modify the original array, we can make a copy. But that would take O(n) extra space. The in-place version is standard for Quickselect.
Let's write the code accordingly.
But note: the above code for the base case (<=5) uses sorting. We can use insertion sort for such a small array, but Python's sort is efficient for 5 elements.
Let's code accordingly.
However, note: the above code for the medians array when the number of medians is >5, we call select recursively. But note: the select function we are writing is for the original array? No, we are calling it on the medians array. So we are using the same function to find the median of the medians. This is correct.
But wait: the select function we wrote is for an array and indices. We are passing medians as the array and 0 and num_medians-1 as the bounds. This is okay.
However, note that the select function we wrote modifies the array it is called on. But in the case of the medians array, we are only interested in the value of the median of medians, not the order of the medians. So it's okay to modify the medians array? Actually, we are passing a list of medians that we created. We don't care about the order of that list after we get the pivot_value. So it's okay.
But note: the original array is being modified. That's acceptable for Quickselect.
Let's write the code.
However, note: the above code for the base case (<=5) does:
code
sub = arr[low:high+1]
sub.sort()
return sub[k]
This creates a copy of the subarray and sorts it. Then returns the k-th element of the sorted copy. But note: k is relative to the subarray? Yes, because we are passing the original k (which is the k-th in the entire array) but when we are in a subarray from low to high, the k we are looking for is the same as the k in the entire array? Actually, note:
code
13. Let's test with the example above:
code
14. But note: in the above example, when we computed the medians for the left part, we had two groups: [1,2,3,4,5] and [6,7]. For the second group, we sorted [6,7] and took the median as the element at index len(group)//2 = 2//2=1? But the group has 2 elements, so index 1 is the second element, which is 7. But we took 6? Wait, we did:
code
group = [6,7]
group.sort() -> [6,7]
median = group[len(group)//2] -> group[2//2] = group[1] = 7.
But in our example, we said we took 6. That was a mistake.
Actually, for a group of 2, the median (lower median) is the first element? But we are using integer division: len(group)//2. For 2, 2//2=1, so we take the second element. That is the upper median.
So we took 7 for the second group. Then medians = [3,7]. Then we sort medians: [3,7] and take index 2//2=1 -> 7.
Then we find an index of 7 in the subarray [1,2,3,4,5,6,7]. It's at index 6? But wait, the entire array at that point is [1,2,3,4,5,6,7] (because we haven't swapped yet). So 7 is at index 6.
Then we swap 7 (index6) with the last element of the subarray (index6) -> no change.
Then partition from 0 to 5 (because we swapped the pivot to index6, and the loop goes from 0 to 5). But wait, the pivot is at index6, and we are partitioning from 0 to 5. Then after the loop, we swap arr[i+1] with arr[6]. The loop:
i=-1
j=0:1<=7 -> i=0, swap arr[0] with arr[0]
j=1:2<=7 -> i=1
j=2:3<=7 -> i=2
j=3:4<=7 -> i=3
j=4:5<=7 -> i=4
j=5:6<=7 -> i=5
Then swap arr[6] (which is 7) with arr[i+1=6] -> no change.
Then pivot_index = 6.
pivot_subarray_index = 6 - 0 = 6.
k=6 -> we return arr[6]=7. Correct.
So the code works even if we take the upper median.
But note: the guarantee of the median of medians algorithm holds for either the lower or upper median? The original paper uses the median of the medians by taking the median of the list of medians. For an even number of medians, it doesn't matter which one we pick because the constant in the guarantee changes by at most 1.
So we are safe.
15. However, note that in the base case (<=5) we are sorting the subarray and returning the k-th element. This is correct.
Let's write the final code.
One more note: the above code for the medians array when the number of medians is more than 5, we recursively call select(medians, 0, num_medians-1, num_medians//2). But note: the medians array is a list of numbers, and we are passing the entire medians array (from index0 to num_medians-1) and k=num_medians//2. This is correct because we want the median of the medians.
We'll write a wrapper:
def median_of_medians(arr, k):
# k is 0-indexed in the entire array.
return select(arr, 0, len(arr)-1, k)
But note: the select function we defined expects k to be the index within the subarray. In the initial call, the entire array is the subarray, so k is the same.
Let's code accordingly.
However, note: the above code does a lot of list slicing for the groups and for the base case. We can avoid slicing by using indices, but for groups of 5 it's acceptable.
But for the base case, we are creating a subarray of at most 5 elements. That's okay.
Let's code.
Median of Medians Algorithm
What is it used for?
The median of medians algorithm is a deterministic pivot selection strategy for selection algorithms like Quickselect. It guarantees worst-case linear time (O(n)) by ensuring the pivot consistently divides the array into reasonably sized partitions, avoiding Quickselect's quadratic worst-case scenario with bad pivots.
Steps of the Algorithm
Given an array A of length n and finding the k-th smallest element (0-indexed):
Base Case:
If n ≤ 5, sort the subarray (using insertion sort or similar) and return the element at index k.
Divide into Groups:
Split A into ⌈n/5⌉ groups of 5 elements each (last group may have fewer).
Find Medians of Groups:
Sort each group (small, fixed size) and extract its median. Collect these medians into a new array M.
Recursively Find Pivot:
Recursively compute the median of M (i.e., the ⌊|M|/2⌋-th smallest element in M). This becomes the pivotp.
Partition Around Pivot:
Partition the original array A around p (using a standard partitioning scheme like Lomuto). Let pivot_index be the final position of p.
Recurse on Correct Partition:
If k = pivot_index, return p.
If k < pivot_index, recurse on left partition A[0..pivot_index-1] with same k.
If k > pivot_index, recurse on right partition A[pivot_index+1..n-1] with k = k - (pivot_index + 1).
Significance for Quickselect's Worst-Case Performance
Standard Quickselect (random pivot) has average (O(n)) time but worst-case (O(n^2)) if pivots are consistently poor.
Median of medians guarantees the pivot is "good enough":
At least 3n/10 elements are ≤ pivot.
At least 3n/10 elements are ≥ pivot.
This ensures each recursive call reduces the problem size by at least a constant fraction (≥ 30%), leading to a recurrence:
(T(n) ≤ T(n/5) + T(7n/10) + O(n))
Which solves to (O(n)) worst-case.
Trade-off: Higher constant factors than random-pivot Quickselect, so rarely used in practice—but crucial for theoretical guarantees in deterministic selection.
Code Implementation
python
def select(arr, low, high, k):
"""
Returns the k-th smallest element in arr[low..high] (0-indexed).
Modifies arr in-place via partitioning.
"""
n = high - low + 1
# Base case: ≤5 elements → sort directly
if n <= 5:
sub = arr[low:high+1]
sub.sort()
return sub[k]
# Step 1: Divide into groups of 5, find medians
medians = []
for i in range(low, high+1, 5):
group_end = min(i+4, high)
group = arr[i:group_end+1]
group.sort()
median = group[len(group)//2] # Lower median for even-sized groups
medians.append(median)
# Step 2: Recursively find median of medians
num_medians = len(medians)
if num_medians <= 5:
medians.sort()
pivot_value = medians[num_medians//2]
else:
pivot_value = select(medians, 0, num_medians-1, num_medians//2)
# Step 3: Partition around pivot_value
# Find an occurrence of pivot_value and swap it to the end
pivot_index = -1
for i in range(low, high+1):
if arr[i] == pivot_value:
pivot_index = i
break
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
# Lomuto partition scheme
i = low - 1
for j in range(low, high):
if arr[j] <= pivot_value:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
pivot_index = i+1 # Final pivot position
# Step 4: Recurse on appropriate partition
relative_pivot = pivot_index - low # Pivot's index in current subarray
if k == relative_pivot:
return arr[pivot_index]
elif k < relative_pivot:
return select(arr, low, pivot_index-1, k)
else:
return select(arr, pivot_index+1, high, k - (relative_pivot + 1))
def median_of_medians(arr, k):
"""
Wrapper: Returns k-th smallest element in arr (0-indexed).
"""
if k < 0 or k >= len(arr):
raise IndexError("k out of bounds")
return select(arr.copy(), 0, len(arr)-1, k) # Use copy to preserve original
Key Notes:
In-place modification: select modifies the input array. Use arr.copy() in the wrapper if preserving the original array is needed.
Deterministic: Guarantees (O(n)) worst-case time, but with larger constants than randomized Quickselect.
Practical use: Rarely used in practice due to overhead, but forms the basis for theoretical worst-case linear-time selection.
We are recursing on subarrays. The k we pass to the recursive call is the same k? Not exactly:
When we recurse on the left part (low to pivot_index-1), we are looking for the k-th element of the entire array, but that element is in the left part. The left part has indices from low to pivot_index-1, and the element we are looking for is at position k in the entire array. But in the left part, the indices are from low to pivot_index-1. So the k-th element of the entire array is the (k - low)-th element of the left part? Actually, no:
Example: entire array indices 0..14. We partition and the pivot is at index 7. If k=6 (the element originally at index 6 in the entire array) is in the left part (0..6). The left part has 7 elements (indices 0..6). The element we are looking for is at index 6 in the entire array, which is the last element of the left part. So in the left part, we are looking for the element at index 6 (in the entire array) which is the 6th element in the left part (if we consider the left part starting at index 0). But note: the left part's first element is at index 0 of the entire array? Actually, the left part is a contiguous segment of the original array. So if we are looking for the k-th element of the entire array and k is in the range [low, pivot_index-1], then in the recursive call we are looking for the same k (because the left part's indices are the same as the entire array's indices for that segment). But wait, in the recursive call we are passing `low` and `pivot_index-1` and `k`. The `k` we pass is the same as the original k? Yes, because the entire array's index k is within the left part. So we are looking for the element at index k in the entire array, and that index is within [low, pivot_index-1]. So we can pass the same k.
Similarly, if we go to the right part, we are looking for the element at index k in the entire array, which is within [pivot_index+1, high]. So we pass the same k.
But note: the base case (<=5) we do:
sub = arr[low:high+1]
sub.sort()
return sub[k]
Here, k is the index in the entire array? But the subarray is from low to high. So the element we want is at position k in the entire array, and since the subarray is a copy of arr[low..high], the element at position k in the entire array is at position (k - low) in the subarray? Actually, no:
Example: entire array: [10,20,30,40,50], low=1, high=3, and we want the element at k=2 (which is 30). The subarray is [20,30,40]. The element 30 is at index 1 in the subarray. So we should return sub[k-low]? But wait, we are passing k=2 and low=1, so k-low=1.
But in the code above, we are returning sub[k]. That would return sub[2] which is 40, which is wrong.
So we have to adjust k for the subarray.
Actually, in the recursive calls, we are always passing the same k (the index in the entire array). But when we look at a subarray, the index of the element we are looking for in that subarray is (k - low). So in the base case, we should do:
return sub[k - low]
But wait, in the base case, we are only called when the subarray has at most 5 elements. And we are given the entire array's index k. So we need to return the element at position (k - low) in the sorted subarray.
Similarly, in the recursive calls for the left and right, we are passing the same k, but note that the entire array's index k is within the subarray. So we don't adjust k in the recursive calls? Actually, we do:
In the recursive call for the left part:
return select(arr, low, pivot_index-1, k)
Here, k is the same as the entire array's index. But the subarray is from low to pivot_index-1. So the element we are looking for is at index k in the entire array, and since low <= k <= pivot_index-1, then in the subarray the element is at position (k - low). But note: the recursive function `select` expects the k-th element of the subarray (i.e., the index within the subarray). But wait, how did we define `select`? We defined it to take `low`, `high`, and `k` (the index in the entire array? or the index within the subarray?).
We have to be consistent.
In the initial call, we pass the entire array and k (0-indexed in the entire array). Then in the recursive calls, we pass the same k (the entire array's index) but with new bounds. But then in the base case, we have to adjust.
Alternatively, we can define `select` to work on the subarray arr[low..high] and look for the k-th smallest element in that subarray (where k is 0-indexed within the subarray). Then we have to adjust k in the recursive calls.
Let's redefine:
We want a function that, given a list `arr` and indices `low` and `high`, and an integer `k` (0 <= k <= high-low), returns the k-th smallest element in arr[low..high].
Then:
Base case: if the subarray has m = high-low+1 elements, and m <=5, we sort the subarray and return the element at index k (in the sorted subarray).
Then when we partition:
We get pivot_index (the index in the entire array? No, in the subarray? Actually, after partition, pivot_index is an index in the entire array? But note: we are partitioning the subarray from low to high. So pivot_index is an index in the entire array, but it is between low and high.
Then we compare k (which is the index within the subarray) with (pivot_index - low). Because in the subarray, the pivot is at position (pivot_index - low).
Then:
if k == pivot_index - low:
return arr[pivot_index]
elif k < pivot_index - low:
return select(arr, low, pivot_index-1, k)
else:
return select(arr, pivot_index+1, high, k - (pivot_index - low + 1))
Wait, that's not exactly: if we go to the right part, we are looking for the (k - (number of elements in left part + 1))-th element in the right part? Actually, the left part has (pivot_index - low) elements (indices from low to pivot_index-1). Then the pivot is at position (pivot_index - low) in the subarray. Then the right part starts at pivot_index+1 and has (high - pivot_index) elements. So if k > (pivot_index - low), then we go to the right part and look for the (k - (pivot_index - low + 1))-th element? Because we skip the left part and the pivot.
Let me clarify:
Subarray: indices low ... high.
After partition:
left part: low ... pivot_index-1 (count = pivot_index - low)
pivot: at pivot_index (count = 1)
right part: pivot_index+1 ... high (count = high - pivot_index)
The k in the subarray (0-indexed) can be:
if k < (pivot_index - low): then the element is in the left part, and we look for the k-th element in the left part (which is the same k because the left part starts at index low and we are counting from 0 within the left part? Actually, the left part's first element is at index low in the entire array, but in the subarray it is at index 0. So the k-th element in the entire array's subarray (which is the k-th smallest in the subarray) is the same as the k-th element in the left part? Wait, the left part is a subarray of the current subarray. The current subarray has elements from low to high. The left part has the smallest (pivot_index - low) elements of the current subarray. So the k-th smallest in the current subarray (with k from 0 to (high-low)) is:
if k < (pivot_index - low): then it is the k-th smallest in the left part (because the left part contains the smallest (pivot_index - low) elements).
if k == (pivot_index - low): then it is the pivot.
if k > (pivot_index - low): then it is the (k - (pivot_index - low + 1))-th smallest in the right part? Actually, we skip the left part (which has (pivot_index - low) elements) and the pivot (1 element), so we subtract (pivot_index - low + 1) from k to get the index in the right part.
Example:
Subarray: [1,2,3,4,5] (low=0, high=4, k=2, we want 3)
Pivot is 3 at index 2 (in the entire array, but also in the subarray).
pivot_index - low = 2.
k==2 -> return pivot? But wait, k=2 is the third element (0-indexed) and we want 3. So yes.
Now if k=3 (the fourth smallest, which is 4). Then:
k (3) > (pivot_index - low) (2)
so we go to the right part and look for the (3 - (2+1) = 0)-th element in the right part? The right part is [4,5] and the 0th element is 4. Correct.
So the recursive calls:
left: select(arr, low, pivot_index-1, k) [with k unchanged because we are looking for the k-th in the left part? But wait, the left part has (pivot_index - low) elements, and k is less than that, so we are looking for the k-th element in the left part. But note: the left part's indices in the entire array are from low to pivot_index-1. The k we are looking for in the entire array's subarray is the same as the k in the left part because the left part is the first (pivot_index - low) elements of the subarray.
right: select(arr, pivot_index+1, high, k - (pivot_index - low + 1))
But note: in the base case, we are given a subarray and a k that is the index within that subarray. So in the base case, we don't adjust k because we are already given the correct index within the subarray.
So we have two options:
Option 1: Keep the current code that passes the entire array's index k and adjust only in the base case? But then in the recursive calls we are passing the same k (the entire array's index) and the bounds. But then in the base case we have to adjust by subtracting low.
Option 2: Change the recursive calls to pass the index within the subarray.
Let's do Option 2 because it is more consistent.
We change the function to:
def select(arr, low, high, k):
# k is the index within the subarray arr[low..high] (0-indexed)
Then:
Base case: if high - low + 1 <= 5:
sub = arr[low:high+1]
sub.sort()
return sub[k] # k is already the index in the subarray.
Then when we partition:
We get pivot_index (in the entire array, but it is between low and high).
The position of the pivot in the subarray is: pivot_index - low.
Then:
if k == pivot_index - low:
return arr[pivot_index]
elif k < pivot_index - low:
return select(arr, low, pivot_index-1, k)
else:
return select(arr, pivot_index+1, high, k - (pivot_index - low + 1))
This is consistent.
But note: in the recursive call for the medians array, we are calling `select(medians, 0, num_medians-1, num_medians//2)`. Here, the medians array is a new array, and we are looking for the median (which is the (num_medians//2)-th element in that array). So that is consistent.
However, in the original call from outside, we want to find the k-th smallest in the entire array. So we call:
select(arr, 0, len(arr)-1, k)
But note: the k we pass is the index in the entire array? Actually, if we define the function to take the index within the subarray, then for the entire array, the index within the entire array is the same as the index in the subarray (because the entire array's subarray from 0 to n-1). So we can pass k (0-indexed in the entire array).
Example: entire array of 10 elements, we want the 3rd smallest (0-indexed 2). Then we call select(arr,0,9,2). Then in the function, we treat k=2 as the index within the subarray [0..9]. That's correct.
So let's adjust the code accordingly.
But wait: in the base case, we do:
sub = arr[low:high+1]
sub.sort()
return sub[k]
Here, k is the index in the subarray. So if the subarray is from low to high, then the element at position k in the subarray is arr[low + k]? But we are returning sub[k] which is the element at index k in the sorted subarray. That is correct because we sorted the subarray and we want the k-th smallest in that subarray.
Example: subarray [20,10,30] (low=1, high=3) and k=1. We sort to [10,20,30] and return sub[1]=20. That is the 1st index (0-indexed) in the subarray, which corresponds to the entire array's index low+1 = 2? But wait, the entire array's index 2 might not be 20? Actually, we are sorting the subarray, so we are returning the 1st smallest in the subarray? No, we are returning the element at index 1 in the sorted subarray, which is the 2nd smallest (since 0-indexed). But note: the subarray has 3 elements. The 0th smallest is 10, the 1st smallest is 20, the 2nd smallest is 30. So if k=1, we return 20. And in the entire array, the element at index 2 (if the subarray starts at index 1) might be something else? But we are only concerned with the k-th smallest in the subarray, not the original index.
So this is correct.
Therefore, we adjust the recursive calls to use the index within the subarray.
Let's rewrite the code accordingly.
Steps:
def select(arr, low, high, k):
# k is 0-indexed within the subarray arr[low..high]
if high - low + 1 <= 5:
sub = arr[low:high+1]
sub.sort()
return sub[k]
medians = []
for i in range(low, high+1, 5):
group_end = min(i+4, high)
group = arr[i:group_end+1]
group.sort()
median = group[len(group)//2]
medians.append(median)
num_medians = len(medians)
if num_medians <= 5:
medians.sort()
pivot_value = medians[num_medians//2]
else:
pivot_value = select(medians, 0, num_medians-1, num_medians//2)
# Find an index of pivot_value in the current subarray [low, high]
pivot_index = -1
for i in range(low, high+1):
if arr[i] == pivot_value:
pivot_index = i
break
# Swap the pivot to the end
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
# Lomuto partition
i = low - 1
for j in range(low, high):
if arr[j] <= pivot_value:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
pivot_index = i+1
# Now pivot_index is the index in the entire array of the pivot.
# The position of the pivot in the current subarray is:
pivot_subarray_index = pivot_index - low
if k == pivot_subarray_index:
return arr[pivot_index]
elif k < pivot_subarray_index:
return select(arr, low, pivot_index-1, k)
else:
return select(arr, pivot_index+1, high, k - (pivot_subarray_index + 1))
This should be correct.
arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
We want the 7th smallest (0-indexed k=6? Wait, the 7th smallest is 7? Actually, the 7th smallest (1-indexed) is 7, which is at index 6 (0-indexed). So k=6.
Steps:
Groups of 5: [1,2,3,4,5] -> median 3
[6,7,8,9,10] -> median 8
[11,12,13,14,15] -> median 13
medians = [3,8,13]
num_medians=3 <=5, so we sort medians: [3,8,13] and take index 1 (3//2=1) -> 8.
Then we find an index of 8 in the entire array (index 7). Swap with last element (index 14) -> [1,2,3,4,5,6,7,15,9,10,11,12,13,14,8]
Then partition from low=0 to high=14 (but note: we are partitioning the entire array? Actually, the current subarray is the entire array because low=0, high=14). We run the loop from 0 to 13.
After partition, the pivot (8) will be placed at index 7? Let's see:
We have: [1,2,3,4,5,6,7,15,9,10,11,12,13,14,8]
i = -1
j=0:1<=8 -> i=0, swap arr[0] with arr[0] -> same
j=1:2<=8 -> i=1
j=2:3<=8 -> i=2
j=3:4<=8 -> i=3
j=4:5<=8 -> i=4
j=5:6<=8 -> i=5
j=6:7<=8 -> i=6
j=7:15<=8? no.
j=8:9<=8? no.
j=9:10<=8? no.
j=10:11<=8? no.
j=11:12<=8? no.
j=12:13<=8? no.
j=13:14<=8? no.
Then swap arr[i+1] (index7) with arr[14] (which is 8) -> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
Now pivot_index = 7.
pivot_subarray_index = 7 - 0 = 7.
k=6 < 7, so we recurse on the left part: select(arr, 0, 6, 6)
Now in the left part [1,2,3,4,5,6,7] (7 elements), we want the 6th element (0-indexed) which is 7.
Then we do the same:
Groups of 5: [1,2,3,4,5] -> median 3
[6,7] -> median 6? (since group of 2, sorted [6,7] -> median at index 0? Actually, for a group of 2, we take the first element? But the algorithm says: for each group, sort and take the median. For even number, we take the lower median? So for [6,7], the lower median is 6.
medians = [3,6]
num_medians=2 <=5, sort -> [3,6], median at index 1//2 = 0? Actually, 2//2=1? Wait, we want the median of medians. For 2 medians, we want the 1st smallest (0-indexed 0) or the 2nd? We are taking the median by index num_medians//2. For 2, that is 1? Actually, 2//2=1, so we take medians[1]=6.
But wait, we have two medians: [3,6]. The median (middle) should be the 1st (0-indexed 0) if we take the lower median? Actually, for 2 elements, the median is the first one? But the algorithm says: take the median of the medians. For an even number, we can take either the lower or the upper. We are using the lower median (by taking index num_medians//2). For 2, that gives index 1? That's the second element. That is the upper median.
Let's check: for 2 elements, the median (as in the middle) is between the two. But we have to choose one. The standard median of medians algorithm uses the lower median? Actually, the original paper uses the median of the medians by taking the median of the list of medians. For an even number, it doesn't matter much because the guarantee still holds with a slight change in the constant.
But note: in our code, we are doing:
if num_medians <= 5:
medians.sort()
pivot_value = medians[num_medians//2]
For 2, num_medians//2 = 1, so we take the second element (6). That is the upper median.
Then we find an index of 6 in the subarray [1,2,3,4,5,6,7]. It's at index 5 (in the entire array? Actually, in the entire array, 6 is at index 5? But note: the entire array is being modified. After the first partition, the entire array is [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]. So 6 is at index 5.
Then we swap it with the last element of the current subarray (which is index 6? Wait, the current subarray is from low=0 to high=6. So the last element is at index 6. We swap index5 (6) with index6 (7) -> [1,2,3,4,5,7,6]
Then we partition from 0 to 5 (because we swapped the pivot to index6, and then we run the loop from 0 to 5). Actually, we are partitioning the subarray from 0 to 6, but we swapped the pivot to index6 (the last of the subarray). Then we run the loop from 0 to 5.
After partition:
We have: [1,2,3,4,5,7,6] and pivot_value=6.
i=-1
j=0:1<=6 -> i=0, swap arr[0] with arr[0] -> same
j=1:2<=6 -> i=1
j=2:3<=6 -> i=2
j=3:4<=6 -> i=3
j=4:5<=6 -> i=4
j=5:7<=6? no.
Then swap arr[i+1] (index5) with arr[6] (which is 6) -> [1,2,3,4,5,6,7]
Now pivot_index = 5.
pivot_subarray_index = 5 - 0 = 5.
k=6? Wait, we are in the recursive call for the left part of the first partition. We called select(arr,0,6,6). But note: the left part has 7 elements (indices 0..6). We are looking for the 6th element in this subarray (0-indexed). That is the last element, which is 7.
But after this partition, pivot_subarray_index=5. k=6 > 5, so we go to the right part.
Right part: from pivot_index+1=6 to high=6 (only one element). And we adjust k: k - (5+1) = 6-6=0.
So we call select(arr,6,6,0) -> base case: subarray [7] (one element) and k=0 -> return 7.
Correct.
So the code works.