kth smallest/largest in a small range 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.

Let's see the code.

Example

 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[] = { 3, 5, 23, 4, 15, 16, 87, 99 }, k = 5;
   cout << findKthSmallestNumber(arr, 7, k) << endl;
   return 0;
}

Output

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

16

Conclusion

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

Updated on: 09-Apr-2021

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements