Given an array arr[] and a number 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. - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Tuesday 14 July 2020

Given an array arr[] and a number 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.

Given an array arr[] and a number K where K is smaller than the size of the array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct.

Corresponding to each test case, print the kth smallest element in a new line.

Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).

Example:
Input:

2
6
7 10 4 3 20 15
3
5
7 10 4 20 15
4

Output:
7
15

Explanation:
Testcase 1:
 3rd smallest element in the given array is 7.
Testcase 2: 4th smallest elemets in the given array is 15.

#include <bits/stdc++.h>

using namespace std;


int main() {

//code

int t;

cin>>t;

while(t--)

{

    int n,m,x,l=0;

    cin>>n;

   int a[100000];

    memset(a,0,sizeof(a));

    for(int i=0;i<n;++i){

    cin>>x;

    a[x]++;

    }

    cin>>m;

    

    for(int i=0;i<100000;++i)

    {

        if(a[i]>0)

        {

            l+=a[i];

        }

        if(l>=m)

        {

         cout<<i<<endl; 

         break;

        }

    }

}

return 0;

}