Below given is the Java code example to find second largest element in an array.
1. Using two temporary variable.
Class SecondLargest{
public static void main(String[] args){
int array[] = {5, 3, 2, 1, 4};
max1 = max2 = array[0];
for(int i = 1; i if ( array[i] > max1 ) {
max2 = max1;
max1 = array[i];
}else if ( array[i] > max2 && array[i] < max1 ){
max2 = array[i];
}
System.out.println("Second largest No. : " + max2);
}
2. Sorting
We can sort the array in descending order. The second largest element will be second element in the array.
3. Bubbling through the array twice.
We can use the bubble sort algrithm to sort the array in descending order, but instead of running the complete bubble sort algorithm we bubble just twice through the array, hence bringing the second largest element to the second position in the array.
1. Using two temporary variable.
Class SecondLargest{
public static void main(String[] args){
int array[] = {5, 3, 2, 1, 4};
max1 = max2 = array[0];
for(int i = 1; i
max2 = max1;
max1 = array[i];
}else if ( array[i] > max2 && array[i] < max1 ){
max2 = array[i];
}
System.out.println("Second largest No. : " + max2);
}
2. Sorting
We can sort the array in descending order. The second largest element will be second element in the array.
3. Bubbling through the array twice.
We can use the bubble sort algrithm to sort the array in descending order, but instead of running the complete bubble sort algorithm we bubble just twice through the array, hence bringing the second largest element to the second position in the array.
No comments:
Post a Comment