-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkthSmallestElement.cpp
More file actions
52 lines (37 loc) · 816 Bytes
/
kthSmallestElement.cpp
File metadata and controls
52 lines (37 loc) · 816 Bytes
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
#include <bits/stdc++.h>
using namespace std ;
int iterate( vector<int> &A , int key ) {
int count = 0;
for ( int i : A )
if ( i <= key )
count++ ;
return count ;
}
int kthsmallest( vector<int> &A, int B) {
int key = 0 ;
if( iterate( A , key ) >= B )
return key ;
key = 1 ;
while( iterate(A,key) < B )
key = key<<1 ;
int a = key>>1 ;
int b = key ;
while( b-a > 1 ) {
int key = (a+b)/2 ;
if ( iterate(A,key) >= B )
b = key ;
else a = key ;
}
if(iterate(A,a) >= B)
return a ;
else return b ;
}
int main(){
vector<int> vec(15) ;
for ( int &i : vec ) i = rand()%50;
for ( int i : vec) cout << i << ' ' ; cout << endl ;
cout << kthsmallest ( vec , 7 ) << endl ;
sort(vec.begin() , vec.end() ) ;
for ( int i : vec) cout << i << ' ' ; cout << endl ;
return 0;
}