- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Articles
- K’th Smallest/Largest Element in Unsorted Array in C++
- C# program to find K’th smallest element in a 2D array
- Rearrange An Array In Order – Smallest, Largest, 2nd Smallest, 2nd Largest,. Using C++
- Find smallest and largest element from square matrix diagonals in C++
- C# program to find Largest, Smallest, Second Largest, Second Smallest in a List
- K’th Least Element in a Min-Heap in C++
- C# Program to get the smallest and largest element from a list
- Finding the second largest element in BST using C++
- Java program to find Largest, Smallest, Second Largest, Second Smallest in an array
- Python program to find Largest, Smallest, Second Largest, and Second Smallest in a List?
- Find largest element from array without using conditional operator in C++
- K’th Boom Number in C++
- Find smallest and largest elements in singly linked list in C++
- kth smallest/largest in a small range unsorted array in C++
- How to find the maximum element of an Array using STL in C++?

Advertisements