-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathQuickSelect_KthSmallestElement.java
More file actions
73 lines (69 loc) · 1.77 KB
/
QuickSelect_KthSmallestElement.java
File metadata and controls
73 lines (69 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//find the kth smallest element in array
//same concept can be used to find kth largest elemen in array
//Time Complexity O(n) (best & average case) O(n^2) worst case
//Space Compelxity O(1)
//bit of quicksort partioning concept is used
//as aplying pivot element partioning pivot element gets its coorect position insorted rray like wise we can find
//the posion of kth smallest i. element at k-1 th index in srted version array
//and for that we dont need to sort the array
import java.util.*;
class A
{
public static void main(String[] args)
{
int[] arr = new int[]{8,5,2,9,7,6,3};
int k = 3;
int result = kthSmallest(arr,k);
System.out.println(k+"th smalest element in array is "+result);
}
public static int kthSmallest(int[] arr,int k)
{
//kth smallest element is found at k-1 in sorted version of the array
int position = k-1;
return kthSmallestHelper(arr,position,0,arr.length-1);
}
public static int kthSmallestHelper(int[] arr,int position,int start,int end)
{
while(true)
{
//choosing first elemnt as pivot element
int pivot = start;
int left = start+1;
int right = end;
while(left<=right)
{
if(arr[left] > arr[pivot] && arr[right] < arr[pivot])
{
swap(left,right,arr);
}
if(arr[left]<=arr[pivot])
{
left++;
}
if(arr[right]>=arr[pivot])
{
right--;
}
}
swap(pivot,right,arr);
if(right==position)
{
return arr[right];
}
else if(right < position)
{
start = right+1;
}
else
{
end = right-1;
}
}
}
public static void swap(int i , int j , int[] arr)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}