

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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.
- Related Questions & Answers
- K’th Smallest/Largest Element in Unsorted Array in C++
- C# program to find K’th smallest element in a 2D array
- Find k-th smallest element in given n ranges in C++
- K-th Smallest Prime Fraction in C++
- K’th Least Element in a Min-Heap in C++
- K-th Smallest in Lexicographical Order in C++
- Find K-th Smallest Pair Distance in C++
- K’th Boom Number in C++
- Find k-th smallest element in BST (Order Statistics in BST) in C++
- K-th smallest element after removing some integers from natural numbers in C++
- N’th palindrome of K digits in C++
- Python program to find k'th smallest element in a 2D array
- Find m-th smallest value in k sorted arrays in C++
- Rearrange An Array In Order – Smallest, Largest, 2nd Smallest, 2nd Largest,. Using C++
- Find k’th character of decrypted string in C++
Advertisements