-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelection.java
More file actions
66 lines (58 loc) · 1022 Bytes
/
Selection.java
File metadata and controls
66 lines (58 loc) · 1022 Bytes
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* 给定一个无序数组,找出其中第K大的元素
* 利用快速排序的partition方法可以实现平均o(n)复杂度
*/
public class Selection {
public static int partition(int[] a,int lo,int hi)
{
int i = lo;
int j = hi+1;
while (true) {
while(a[++i]<a[lo])
{
if(i>=hi) break;
}
while (a[--j]>a[lo]) {
if(j<=lo) break;
}
if(i>=j)
break;
swap(a,i,j);
}
swap(a, lo, j);
return j;
}
public static int selection(int[] a,int k)
{
int lo = 0;
int hi = a.length-1;
int j = 0;
while(true)
{
j=partition(a, lo, hi);
if (j==k-1) {
break;
}
else if(j<k)
{
lo=j+1;
}
else
{
hi = j-1;
}
}
return a[j];
}
public static void swap(int[] arr,int i,int j)
{
int temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = {2,1,3,4,5};
System.out.println(selection(a, 4));
}
}