Java interview Program to find second smallest number in an integer array without sorting the elements.
- package com.instanceofjava;
- class SecondSmallestNumber{
- int[] x ={10,11,12,13,14,6,3,-1};
- int small=x[0];
- for(int i=0;i<x.length;i++)
- {
- if(x[i]<small)
- {
- small=x[i];
- }
- }
- int sec_Small=x[0];
- for(int i=0;i<x.length;i++)
- {
- if(x[i]<sec_Small && x[i]!=small)
- {
- sec_Small=x[i];
- }
- }
- System.out.println("Second Smallest Number: "sec_Small);
- }
- }
Output:
- Second Smallest Number:3
Java interview Program to find second Smallest number in an integer array by sorting the elements.
- package com.instanceofjava;
- class SecondSmallestNumber{
- public static void main(String args[])
- {
- int numbers[] = {6,3,37,12,46,5,64,21};
- Arrays.sort(numbers);
- System.out.println("Smallest Number: "+numbers[0]);
- System.out.println("Second Smallest Number: "+numbers[1]);
- }
- }
Output:
- Smallest Number: 3
- Second Smallest Number: 5
Hi in the first program if u have smallest number in 1st position in the array then the code will not work
ReplyDelete