- Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathQuickSelect.java
More file actions
Latest commit
55 lines (45 loc) · 1.77 KB
/
Copy pathQuickSelect.java
File metadata and controls
55 lines (45 loc) · 1.77 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
// Path: Java\Searching\QuickSelect.java
// Java program to kth smallest element using quickSelect Algorithm.
// Time-Complexity: O(N^2), where N is the size of array.
importjava.util.Random;
publicclassQuickSelect {
// Function to swap two elements in the array
privatestaticvoidswap(int[] arr, inta, intb) {
inttemp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
// Partition function to rearrange elements around the pivot
privatestaticintpartition(int[] arr, intleft, intright, intpivotIndex) {
intpivotValue = arr[pivotIndex];
swap(arr, pivotIndex, right); // Move pivot to the end
intstoreIndex = left;
for (inti = left; i < right; i++) {
if (arr[i] < pivotValue) {
swap(arr, i, storeIndex);
storeIndex++;
}
}
swap(arr, storeIndex, right); // Move pivot to its final place
returnstoreIndex;
}
// Quickselect function
privatestaticintquickSelect(int[] arr, intleft, intright, intk) {
if (left == right)
returnarr[left];
intpivotIndex = left + newRandom().nextInt(right - left + 1);
pivotIndex = partition(arr, left, right, pivotIndex);
if (k == pivotIndex)
returnarr[k];
elseif (k < pivotIndex)
returnquickSelect(arr, left, pivotIndex - 1, k);
else
returnquickSelect(arr, pivotIndex + 1, right, k);
}
publicstaticvoidmain(String[] args) {
int[] arr = {3, 8, 2, 5, 1, 4, 7, 6};
intk = 4; // Find the 4th smallest element
intresult = quickSelect(arr, 0, arr.length - 1, k - 1);
System.out.println("The " + k + "-th smallest element is: " + result);
}
}