K’th Smallest/Largest Element using STL in C++

C++Server Side ProgrammingProgramming

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.
  • Initialise a empty ordered set.
  • Iterate over the array and insert each element to the array.
  • Iterate over the set from 0 to k - 1.
  • Return the value.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findKthSmallestNumber(int arr[], int n, int k) {
   set<int> set;
   for (int i = 0; i < n; i++) {
      set.insert(arr[i]);
   }
   auto it = set.begin();
   for (int i = 0; i < k - 1; i++) {
      it++;
   }
   return *it;
}
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.

raja
Published on 09-Apr-2021 12:53:39
Advertisements