Finding the 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.
The following steps are involved in finding the smallest element using sorting.
Sort the given array in ascending order using a sorting algorithm like merge sort, bubble sort, or heap sort.
Return the element at index in the sorted array.
The illustration below further explains this concept:
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 arraysort(arr, arr + size);// Finding the third smallest element in the arraycout << "The third smallest element in the array is: "<<arr[2]<<endl;return 0;}
Free Resources