-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKthSmallestElement.java
56 lines (43 loc) · 1.37 KB
/
KthSmallestElement.java
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
class Solution{
public static int partition(int[] arr, int l, int r)
{
int x = arr[r], i = l;
for (int j = l; j <= r - 1; j++) {
if (arr[j] <= x) {
// Swapping arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
}
}
// Swapping arr[i] and arr[r]
int temp = arr[i];
arr[i] = arr[r];
arr[r] = temp;
return i;
}
public static int kthSmallest(int[] arr, int l, int r, int k)
{
//Your code here
if (k> 0 && k <= r - l + 1) {
// Partition the array around last
// element and get position of pivot
// element in sorted array
int pos = partition(arr, l, r);
// If position is same as k
if (pos - l == k - 1)
return arr[pos];
// If position is more, recur for
// left subarray
if (pos - l > k - 1)
return kthSmallest(arr, l, pos - 1, k);
// Else recur for right subarray
return kthSmallest(arr, pos + 1, r,
k - pos + l - 1);
}
// If k is more than number of elements
// in array
return Integer.MAX_VALUE;
}
}