Find the kth smallest element from an array using sorting

Finding the kthk^{th} smallest element of an array (efficiently) may seem a little tricky at first; however, it can easily be found using a min-heap or by sorting the array.

Algorithm

The following steps are involved in finding the kthk^{th} smallest element using sorting.

  1. Sort the given array in ascending order using a sorting algorithm like merge sort, bubble sort, or heap sort.

  2. Return the element at index k1k - 1 in the sorted array.

The illustration below further explains this concept:

Consider the array shown above.
1 of 4

Implementation

The following code snippet implements the above algorithm in C++:

#include <iostream>
#include<algorithm>
using namespace std;
int main() {
int arr[] = {10, 1, 0, 8, 7, 2};
int size = sizeof(arr)/sizeof(arr[0]);
// Sorting the array
sort(arr, arr + size);
// Finding the third smallest element in the array
cout << "The third smallest element in the array is: "<<
arr[2]<<endl;
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved