In the code below I was given unsorted array had to find kth smallest Given an array arr[] and an integer K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct.
#include<bits/stdc++.h>
using namespace std;
Merge function:
void merge(int arr[],int l,int m,int r){
int marr[(r-l)+1];
int i=l,j=m+1,k=0;
for(k;k<=(r-l);k++){
if(i==(m+1)){
marr[k]=arr[j];
j++;
}
else if(j==(r+1)){
marr[k]=arr[i];
i++;
}
else if(arr[i]<=arr[j]){
marr[k]=arr[i];
i++;
}
else if(arr[i]>arr[j]){
marr[k]=arr[j];
j++;
}
}
//Below assignment was creating wrong output but cant figure out why?
for(k=0;k<=(r-l);k++,l++){
arr[l]=marr[k];
}
//However below code worked instead, in spite tracing same no. of values
//for(int x=l,k=0;x<=r;x++,k++){
// arr[x]=marr[k];
//}
Mergesort:
void mergesort(int arr[], int l,int r){
if(r<=l)
return;
int mid=l+(r-l)/2;
mergesort(arr,l,mid);
mergesort(arr,mid+1,r);
merge(arr,l,mid,r);
}
class Solution{
public:
// 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
int kthSmallest(int arr[], int l, int r, int k) {
mergesort(arr,l,r);
return arr[k-1];
}
};
Driver Code starts
int main()
{
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;
Solution ob;
cout<<ob.kthSmallest(a, 0, number_of_elements-1, k)<<endl;
}
return 0;
}
Driver Code ends