-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKthSmallestNo.cpp
52 lines (47 loc) · 904 Bytes
/
KthSmallestNo.cpp
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
// Kth Smallest Element using Quick Select
// https://practice.geeksforgeeks.org/problems/kth-smallest-element/0
#include<iostream>
using namespace std;
int findK(int arr[],int l,int r){
int pivot = arr[r];
int j = l;
for(int i = l;i<=r;i++){
if(arr[i]<=pivot){
swap(arr[i],arr[j]);
j++;
}
}
return j-1;
}
void solve(){
int N;int K;
int arr[10];
cin>>N;
for(int i = 0;i<N;i++)
cin >> arr[i];
cin>>K;
int index = findK(arr,0,N-1);
while(true){
if(index == K-1){
cout<<arr[index]<<"\n";
return;
}
else if(index < K-1){
index = findK(arr,index+1,N-1);
}
else {
index = findK(arr,0,index-1);
}
}
}
int main()
{
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
int T;
cin>>T;
while(T--){
solve();
}
return 0;
}