Find Smallest and Second smallest element in array.

Find Smallest and Second smallest number in array.

Given a integer array, find smallest and second smallest number in array.

Lets understand the problem statement graphically and it will be more clear,
find smallest and second smallest element in an array in java
Find smallest and second smallest element in an array in Java

Algorithm


There are many approach to solve this problem, Lets see one of the efficient way.
  1. Take 2 variable "min" and "secondMin" and initialize both to first element of array.
    int min = arr[0]
    int secondMin = arr[0]
  2. 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.


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.

Post a Comment