There are many approach to solve this problem, Lets see one of the efficient way.
- Take 2 variable "min" and "secondMin" and initialize both to first element of array.
int min = arr[0]
int secondMin = arr[0] - Iterate through array and for each value of array, check,
- if the current value in array is < "min" then update "secondMin" with "min" value and "min" with new minimum value found.
- if the current value in array is > "min" but < then "secondMin" then update "secondMin" with new second minimum element found.
Java program to find smallest and second smallest element in array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | package javabypatel; public class FindSmallestAndSecondSmallestNumberArray { public static void main(String[] args) { int [] arr = new int []{ 1 , 1 , 3 , 1 , 5 , 4 }; findSmallestAndSecondSmallestNumberArray(arr); } private static void findSmallestAndSecondSmallestNumberArray( int [] arr){ if (arr== null || arr.length < 2 ){ System.out.println( "Invalid Input" ); return ; } int smallest = arr[ 0 ]; int secondSmallest = arr[ 0 ]; for ( int value : arr) { if (value < smallest){ secondSmallest = smallest; smallest = value; } else if (smallest == secondSmallest || (value < secondSmallest && value != smallest)){ secondSmallest = value; } } if (secondSmallest == smallest){ System.out.println( "Smallest number : " +smallest); System.out.println( "Second smallest number : not found" ); } else { System.out.println( "Smallest number : " +smallest); System.out.println( "Second smallest number :" +secondSmallest); } } } |
You may also like to see
Find Largest and Smallest number in Array
Count zeros in a row wise and column wise sorted matrix
Find middle element of a linked list
Union and Intersection of Two Sorted Arrays
Merge two sorted arrays in Java
How is ambiguous overloaded method call resolved in java
Enjoy !!!!
If you find any issue in post or face any error while implementing, Please comment.