-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSelect.java
More file actions
68 lines (49 loc) · 1.18 KB
/
QuickSelect.java
File metadata and controls
68 lines (49 loc) · 1.18 KB
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
67
68
package kent.alg.recursive;
import java.util.Random;
public class QuickSelect {
private int[] nums;
public QuickSelect(int[] nums) {
this.nums = nums;
}
public int select(int k) {
return select(0, nums.length - 1, k-1);
}
private int select(int firstIndex, int lastIndex, int k) {
int pivot = partition(firstIndex, lastIndex);
if(pivot > k)
{
select(firstIndex, pivot - 1, k);
}
else if(pivot < k)
{
select(pivot + 1, lastIndex, k);
}
return nums[k];
}
private int partition(int firstIndex, int lastIndex) {
int pivot = new Random().nextInt(lastIndex - firstIndex + 1) + firstIndex;
swap(firstIndex, pivot);
for(int i=firstIndex; i<lastIndex; i++) {
if(nums[i] > nums[lastIndex]) {
swap(i, firstIndex);
firstIndex ++;
}
}
swap(firstIndex, lastIndex);
return firstIndex;
}
private void swap(int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
/**
* find the 2 largest number in array. O(n log n)
* @param args
*/
public static void main(String[] args) {
int[] nums = {1,5,4,8,-2};
QuickSelect q = new QuickSelect(nums);
System.out.println( q.select(2));
}
}