Java program to find second largest number in an array ?

Answer : Given an array of integers, our task is to write a program…

Java program to find second largest number in an array ?

  • Given an array of integers, our task is to write a program that efficiently finds the second largest element present in the array.

Algorithm:

  • Initialize two variables first and second to INT_MIN as,
    • first = second = INT_MIN

a) If the current element in array say arr[i] is greater than first. Then update first and second as,

    • second = first
    • first = arr[i]
    b) If the current element is in between first and second, then update second to store the value of current variable as

    • second = arr[i]
  • Return the value stored in second.

step 1

  • Iterate the given array.

Step 2 (first if condition arr[i] > largest):

  • If current array value is greater than largest value then move the largest value to secondLargest and make current value as largest

Step 3 (second if condition arr[i] >secondLargest )

  • If the current value is smaller than largest and greater than secondLargest then the current value becomes secondLargest.

Sample code in Java

[pastacode lang=”java” manual=”public%20class%20SecondLargest%20%7B%0A%20%20%20%20%20%0A%20%20%20%20%09public%20static%20void%20main(String%5B%5D%20args)%20%7B%0A%20%20%20%20%20%0A%20%20%20%20%09%09int%20arr%5B%5D%20%3D%20%7B%2024%2C%2056%2C%2057%2C%20105%2C%20102%2C%2062%2C%2058%2C%2046%2C%2076%2C%2095%20%7D%3B%0A%20%20%20%20%09%09int%20largest%20%3D%20arr%5B0%5D%3B%0A%20%20%20%20%09%09int%20secondLargest%20%3D%20arr%5B0%5D%3B%0A%20%20%20%20%09%09%0A%20%20%20%20%09%09System.out.println(%22The%20given%20array%20is%3A%22%20)%3B%0A%20%20%20%20%09%09for%20(int%20i%20%3D%200%3B%20i%20%3C%20arr.length%3B%20i%2B%2B)%20%7B%0A%20%20%20%20%09%09%09System.out.print(arr%5Bi%5D%2B%22%5Ct%22)%3B%0A%20%20%20%20%09%09%7D%0A%20%20%20%20%09%09for%20(int%20i%20%3D%200%3B%20i%20%3C%20arr.length%3B%20i%2B%2B)%20%7B%0A%20%20%20%20%20%0A%20%20%20%20%09%09%09if%20(arr%5Bi%5D%20%3E%20largest)%20%7B%0A%20%20%20%20%09%09%09%09secondLargest%20%3D%20largest%3B%0A%20%20%20%20%09%09%09%09largest%20%3D%20arr%5Bi%5D%3B%0A%20%20%20%20%20%0A%20%20%20%20%09%09%09%7D%20else%20if%20(arr%5Bi%5D%20%3E%20secondLargest)%20%7B%0A%20%20%20%20%09%09%09%09secondLargest%20%3D%20arr%5Bi%5D%3B%0A%20%20%20%20%20%0A%20%20%20%20%09%09%09%7D%0A%20%20%20%20%09%09%7D%0A%20%20%20%20%20%0A%20%20%20%20%09%09System.out.println(%22%5CnSecond%20largest%20number%20is%3A%22%20%2B%20secondLargest)%3B%0A%20%20%20%20%20%0A%20%20%20%20%09%7D%0A%20%20%20%20%7D” message=”” highlight=”” provider=”manual”/]

Output

The given array is:
24	56	57	105	 102  62  58  46  76  95	
Second largest number is:102
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like