# Program to find Kth smallest element in an unsorted array

Program to find the Kth smallest element in an unsorted array is discussed here. Given an integer array, write a program to print the kth smallest number from the array.

For example,

Sample Input:

10 (Number of elements of the array)
5 (Kth smallest element to be found)
1 2 7 8 9 3 4 5 6 0 (Array elements)

Sample Output:

4

## Algorithm to find the Kth smallest element in an unsorted array

• Input the number of elements of the array.
• Input the Kth element to be found.
• Input the elements of the array.
• Sort the array.
• Return the arr[k-1].

Program to find the Kth smallest element in an unsorted array is given below.

#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,k;
cin>>n>>k;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
cout<<a[k-1];
}

Test Case 1

I/P

10 5

1 2 7 8 9 3 4 5 6 0

O/P

4

Test Case 2

I/P

10 1

1 2 7 8 9 3 4 5 6 0

O/P

0

Test Case 3

I/P

10 10

1 2 7 8 9 3 4 5 6 0

O/P

9

Test Case 4

I/P

10 6

1 2 3 4 59 8 7 6 0 9

O/P

6

Test Case 5

I/P

10 4

1 2 3 4 59 8 7 6 0 9

O/P

3