 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
K’th Smallest/Largest Element using STL 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.
- 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.
#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.
Advertisements
 