Java interview Program to find second smallest number in an integer array without sorting the elements.


  1. package com.instanceofjava;
  2. class SecondSmallestNumber{
  3.  
  4. int[] x ={10,11,12,13,14,6,3,-1};
  5.  
  6.         int small=x[0];
  7.  
  8.  for(int i=0;i<x.length;i++)
  9.  {
  10.         if(x[i]<small)
  11.         {
  12.         small=x[i];
  13.         }
  14.  }
  15.  
  16.    int sec_Small=x[0];
  17.  
  18. for(int i=0;i<x.length;i++)
  19.  {
  20.         if(x[i]<sec_Small && x[i]!=small)
  21.         {
  22.         sec_Small=x[i];
  23.         }
  24.   }
  25.  
  26.         System.out.println("Second Smallest Number: "sec_Small);
  27.         }
  28. }



Output:
 
  1. Second Smallest Number:3

Java interview  Program to find second Smallest number in an integer array by sorting the elements.


  1. package com.instanceofjava;
  2. class SecondSmallestNumber{
  3.  
  4. public static void main(String args[])
  5.  
  6. int numbers[] = {6,3,37,12,46,5,64,21};
  7.  
  8.   Arrays.sort(numbers);
  9.  
  10.   System.out.println("Smallest Number: "+numbers[0]);
  11.   System.out.println("Second Smallest Number: "+numbers[1]);

  12.  }
  13.  
  14. }




Output:
 
  1. Smallest Number: 3
  2. Second Smallest Number: 5



Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

1 comments for Find Second smallest number in java without sorting

  1. Hi in the first program if u have smallest number in 1st position in the array then the code will not work

    ReplyDelete

Select Menu