k-th Largest Element (Quickselect)
Problem
Print the k-th biggest number of the array (counting duplicates: in 5 5 3 the 2nd biggest is 5). Quickselect finds it without sorting the whole array: it partitions around a pivot and continues only in the side that holds the answer.
Constraints
- 1 <= n <= 10^5
- 1 <= k <= n
Examples
Input
6 3 2 1 5 6 4 2
Output
5
Solutions
After one partition the pivot stands at its final sorted place. If that is the target index we are done; otherwise only one side needs more work. The average cost is O(n); a bad pivot can make it O(n^2).
/*
* Problem : k-th largest.
* Input : n, the array, then k.
* Output : The number.
* Approach: Quickselect.
* Time : O(n) average
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static int solve(int[] a, int k) {
// Step 1: Work on a copy. In ascending order the answer sits at index target = n - k.
int[] data = a.clone();
int target = data.length - k;
int low = 0;
int high = data.length - 1;
while (low < high) {
// Step 2: Partition: move the middle value to the end as the pivot. Smaller numbers go to the left side.
int middle = low + (high - low) / 2;
int temp = data[middle];
data[middle] = data[high];
data[high] = temp;
int pivot = data[high];
int store = low;
for (int i = low; i < high; i++) {
if (data[i] < pivot) {
temp = data[i];
data[i] = data[store];
data[store] = temp;
store++;
}
}
temp = data[store];
data[store] = data[high];
data[high] = temp;
// Step 3: The pivot is now at its final place "store". Continue only on the side that holds the target.
if (store == target) {
return data[store];
} else if (store < target) {
low = store + 1;
} else {
high = store - 1;
}
}
return data[target];
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
int k = scanner.nextInt();
System.out.println(solve(a, k));
}
}
Hints (2)
- Where does the pivot end up after partition?
- Why do we only follow one side?