-
Notifications
You must be signed in to change notification settings - Fork 0
/
(ARRAY)KTHAMALLESTELEMENTINANARRAY.cpp
83 lines (71 loc) · 1.52 KB
/
(ARRAY)KTHAMALLESTELEMENTINANARRAY.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// { Driver Code Starts
//Initial function template for C++
#include<bits/stdc++.h>
using namespace std;
int kthSmallest(int *, int, int, int);
int main()
{
// ios_base::sync_with_stdio(false);
// cin.tie(NULL);
int test_case;
cin>>test_case;
while(test_case--)
{
int number_of_elements;
cin>>number_of_elements;
int a[number_of_elements];
for(int i=0;i<number_of_elements;i++)
cin>>a[i];
int k;
cin>>k;
cout<<kthSmallest(a, 0, number_of_elements-1, k)<<endl;
}
return 0;
}// } Driver Code Ends
//User function template for C++
// arr : given array
// l : starting index of the array i.e 0
// r : ending index of the array i.e size-1
// k : find kth smallest element and return using this function
void insert(int a[],int x){
int i=x,t=a[x];
while(i>0 && t>a[i/2]){
a[i]=a[i/2];
i=i/2;
}
a[i]=t;
}
void swap(int *x,int *y){
int t;
t=*x;
*x=*y;
*y=t;
}
void deletea( int a[],int n){
int val=a[0],t=a[n];
a[0]=a[n];
a[n]=val;
int i=0,j=2*i;
while(j<=n-1){
if(j<n-1 && a[j+1]>a[j])
j=j+1;
if(a[j]>a[i])
{
swap(&a[i],&a[j]);
i=j;
j=2*j;
}
else
break;
}
}
int kthSmallest(int arr[], int l, int r, int k) {
//code here
for(int i=l;i<=r;i++){
insert(arr,i);
}
for(int i=r;i>l;i--){
deletea(arr,i);
}
return arr[k-1];
}