java programs

Find first largest number and second largest number in unsorted array in java

package com.technicalexplorer;

public class SecondLargest {
public static void main(String[] args) {
int a[] = {5, 10, 2, 4, -2};
topTwoLargestNumbers(a);
}

public static void topTwoLargestNumbers(int[] array) {
if(array == null || array.length < 2) {
System.out.println("Insufficient data! Elements in array are less than 2!!");
} else {
int length = array.length;
int firstLargest = array[0];
int secondLargest = array[1];
for(int i=1; i<length; i++) {
//the condition should be less than or equal because there may be
//2 largest numbers in the array in that case we have display
//largest number as first and second largest number.
if(firstLargest <= array[i]) {
//first assign first Largest element to second largest element
//then assign current element to first largest number.
secondLargest = firstLargest;
firstLargest = array[i];
} else if(secondLargest < array[i]) {
secondLargest = array[i];
}
}
System.out.println("First largest of given array is " + firstLargest);
System.out.println("Second largest of given array is " + secondLargest);
}
}
}

Sample Output:

First largest of given array is 10

Second largest of given array is 5

Powered by Blogger.