K’th Smallest/Largest Element in Unsorted Array in C++


In this tutorial, we are going to write a program that finds the k-th smallest number in the unsorted array.

Let's see the steps to solve the problem.

  • Initialise the array and k.
  • Sort the array using sort method.
  • Return the value from the array with the index k - 1.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findKthSmallestNumber(int arr[], int n, int k) {
   sort(arr, arr + n);
   return arr[k - 1];
}
int main() {
   int arr[] = { 45, 32, 22, 23, 12 }, n = 5, k = 3;
   cout << findKthSmallestNumber(arr, n, k) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

23

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 09-Apr-2021

124 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements