In this blog, we give a solution for Quick Select.
Here, we have an improvement. The idea is to randomly pick a pivot element.
Main difference is how we implement partition.
public int nextInt(int bound)
Returns a pseudorandom, uniformly distributed
int
value between 0 (inclusive) and the specified value (exclusive).int idx = new Random().nextInt(nums.length);
int random = (nums[idx]);
Codes
public class Solution {
private int partition(int[] nums, int start, int end) {
int pivot = nums[end];
int currentSmaller = start - 1;
for (int i = start; i < end; i++) {
if (nums[i] < pivot) {
currentSmaller++;
swap(nums, i, currentSmaller);
}
}
currentSmaller++;
swap(nums, end, currentSmaller);
return currentSmaller;
} public int randomPartition(int[] nums, int start, int end) {
int length = end - start + 1;
int idx = new Random().nextInt(length);
int randomIndex = idx + start;
swap(nums, last, randomIndex);
partition(nums, start, end);
}
}
The assumption in the analysis is, random number generator is equally likely to generate any number in the input range.
The worst case time complexity of the above solution is still O(n2). In worst case, the randomized function may always pick a corner element. The expected time complexity of above randomized QuickSelect is Θ(n), see CLRS book or MIT video lecture for proof.