algo. kth largest element in an array

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.*;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] q = new int[n];

for (int i = 0; i < n; i++) {
q[i] = sc.nextInt();
}

System.out.print(find_min_k(q, 0, n - 1, k));
}

public static int find_min_k(int[] q, int l, int r, int k) {
if (l == r) {
return q[l];
}

int x = q[l + r >> 1];
int i = l - 1, j = r + 1;

while (i < j) {
do i++; while (q[i] < x);
do j--; while (q[j] > x);
if (i < j) {
int t = q[i];
q[i] = q[j];
q[j] = t;
}
}

int rank = j - l + 1;
if (k <= rank) return find_min_k(q, l, j, k);
else return find_min_k(q, j + 1, r, k - rank);
}
}

algo. kth largest element in an array
http://elwinliu.com/2024/09/08/kth_element/
Author
Elwin
Posted on
September 8, 2024
Licensed under