Program to find the second largest element in an array

This program helps you to find the second largest element in an array. There are many methods by which we can find the second largest element. I am using a method which has the lowest time complexity - O(n). Here we are first finding the largest element in an array by traversing each element. In the next iteration, we are checking whether each element is less than the largest element and thus assigning its value to second largest element.

There are some other methods like sorting the array and traversing from n-2 th element to 0th element to check whether it is different from n-1 th element and returning the value. This will take a time complexity of O(n logn).


package com.programs;

/*
 * Java program to get the second largest element in an array
 */

public class secondLargest {

 public static int findSecondLargest(int arr[]) {
  int length = arr.length;
  int large, slarge, flag = 0;
  large = arr[0];
  slarge = arr[0];
  for (int i = 0; i < length; i++) {
   if (large < arr[i]) {
    large = arr[i];
   }
  }
  for (int i = 0; i < length; i++) {
   if (large != arr[i]) {
    slarge = arr[i];
    flag = 1;
    break;
   }
  }

  // to check whether the array contains only one value or not

  if (flag != 1) {
   slarge = large;
   return slarge;
  }
  for (int i = 0; i < length; i++) {
   if ((slarge < arr[i]) && (arr[i] < large)) {
    slarge = arr[i];
   }
  }
  return slarge;
 }
}
}

The JUnit test cases for this class is as follows:

package com.unitTest;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.programs.secondLargest;

public class testForSecondLargest {

 @Test
 public void testCases() {
  int arr[] = { 100, 6, 10, 7, 11, 12, 3, 2, 100, 17, 8, 9, 100, 91, 981,
    5 };
  assertEquals(100, secondLargest.findSecondLargest(arr));

  int arr2[] = { -40, -30, -17, -15, -23, 0, -31 };
  assertEquals(-15, secondLargest.findSecondLargest(arr2));

 }

}

Both the test cases passed successfully.

Similar Programs:
1) Conversion of String to Int using Java
2) Java program to check if a string is a pangram
3) Java program to check if array is bitonic

Comments

Popular posts from this blog

Difference between "diff" and "sdiff" commands in Unix

Anonymous classes in C++