Java example of finding the second largest element of an array

  • 2020-04-01 03:17:49
  • OfStack

Assume that all the Numbers in the array are non-negative integers, and all the Numbers are different.


package array;
public class SecondMaxElem {

 public static int getSecondMaxElem(int[] array) {

  if(array == null || array.length <=  1) {
   return -1;
  }

  int max = array[0] > array[1] ? array[0] : array[1];
  int secMax = array[0] + array[1] - max;
  int len = array.length;
  for(int i = 2; i < len; i++) {
   int cur = array[i];
   if(cur > secMax) {
    secMax = cur;

    if(secMax > max) {   // swap
     int temp = secMax;
     secMax = max;
     max = temp;
    }
   }
  }

  return secMax;
 }

 public static int getSecondMaxElem2(int[] array) {

  if(array == null || array.length <=  1) {
   return -1;
  }

  int max = array[0] > array[1] ? array[0] : array[1];
  int secMax = array[0] + array[1] - max;
  int len = array.length;
  for(int i = 2; i < len; i++) {
   int cur = array[i];
   if(cur > max) {
    secMax = max;
    max = cur;
   }
   else if(cur > secMax && cur < max) {
    secMax = cur;
   }
   else {
    //Other cases where the maximum and the second largest values don't change, you can draw an axis
   }
  }

  return secMax;
 }

 public static void main(String[] args) {
  int[] array = new int[] {  };
 

  array = new int[] { 2, 3, 1, 6, 7, 5, 9 };
  System.out.println(" algorithm 1 :  " + getSecondMaxElem(array));
  System.out.println(" algorithm 2 :  " + getSecondMaxElem2(array));



 }
}


Related articles: