This post is completed by 1 user

  • 0
Add to List
Beginner

397. Find Third Smallest elements in a given array

Objective: Given an array of integers, write an algorithm to find the third smallest element in the array.

Example:

Int [] a = { 6, 8, 1, 9, 2, 10};
Output: Third smallest element is: 6

Int [] a = { 6, 8, 1, 9, 2, 1, 10, 10};
Output: Third smallest element is: 2

Int [] a = {6};
Output: Invalid Input, array size is less than 3

Approach:

  1. Take three variables; let's call them first, second and third and mark them as +∞.
  2. Iterate through the array and for each element (let's call it current),  
    1. Check if first>current, assign the first value to the second and second value to third and assign current to first.
    2. If the above step is not true then the current element might be a candidate of the second smallest element, so check if current<second, if yes then assign second value to third and assign current to second.
    3. If the above step is not true then the current element might be a candidate of the third-smallest element, so check if current<third, if yes then assign current to third.
  3. At the end print the third, it will third-smallest element in the array

See the code below for more understanding. 

Output:

Third smallest element is: 6