Uh oh!
There was an error while loading. Please reload this page.
forked from iiitv/algos
- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathQuickSelect.java
More file actions
Latest commit
64 lines (61 loc) · 2.16 KB
/
Copy pathQuickSelect.java
File metadata and controls
64 lines (61 loc) · 2.16 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
publicclassQuickSelect {
/*
* partition function
* array : array on which partitioning has to be done
* left : left index of the partitioning subarray
* right : right index of the partitioning subarray
* pivotIndex : pivot index from which partition has to done
* return : the index of the last element of the left subarray
*/
privatestaticintpartition(int[] array, intleft, intright, intpivotIndex) {
intpivotValue = array[pivotIndex];
inttemp = array[right];
array[right] = array[pivotIndex];
array[pivotIndex] = temp;
intstoreIndex = left;
while (left < right) {
if (array[left] < pivotValue) {
temp = array[storeIndex];
array[storeIndex] = array[left];
array[left] = temp;
storeIndex++;
}
left++;
}
temp = array[right];
array[right] = array[storeIndex];
array[storeIndex] = temp;
returnstoreIndex;
}
/*
* Quick Select function
* left : left index of the subarray
* right : right index of the subarray
* pos : position to find the element using quick sort
* return : the value of element at pos place in the sorted array
*/
publicstaticintquickSelect(int[] array, intleft, intright, intpos) {
intpivotIndex;
if(pos < 0 || pos >= array.length) {
thrownewIndexOutOfBoundsException("index: " + pos);
}
if (left == right) {
returnarray[left];
}
pivotIndex = right - 1;
pivotIndex = partition(array, left, right, pivotIndex);
if (pos == pivotIndex) {
returnarray[pivotIndex];
}
elseif (pos < pivotIndex) {
returnquickSelect(array, left, pivotIndex - 1, pos);
}
else {
returnquickSelect(array, pivotIndex + 1, right, pos);
}
}
publicstaticvoidmain(String[] args) {
int[] array = {10, 5, 1, 6, 7, 3, 2, 4, 8, 9};
System.out.println(quickSelect(array, 0, array.length - 1, 3));
}
}