Write a program to get second highest number in an array using PHP ?

• Last Updated : 07 Oct, 2021

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

Example:

Input: arr[] = {13, 14, 15, 16, 17, 18}
Output: The second largest element is 17.
Explanation: The largest element of the array
is 35 and the second largest element is 17

Input: arr[] = {10, 5, 10}
Output: The second largest element is 5.
Explanation: The largest element of the array
is 10 and the second largest element is 5

Input: arr[] = {10, 10, 10}
Output: The second largest does not exist.
Explanation: Largest element of the array
is 10 there is no second largest element

Simple Solution:

Approach: The idea is to sort the array in descending order and then return the second element which is not equal to the largest element from the sorted array.

PHP



Output
Second Largest element is 64

Complexity Analysis:

Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
Auxiliary Space: O(1)

Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.
Sorting In Place: Yes
Stable: Yes

Another Approach: Find the second largest element in a single traversal.

Below is the complete algorithm for doing this:

1) Initialize the first as 0 (i.e, index of arr element)
2) Start traversing the array from array,
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]
3) Return the value stored in second.

PHP

 \$first) {            \$second = \$first;            \$first = \$arr[\$i];        }          // If arr[i] is in        // between first and        // second then update        // second        else if (\$arr[\$i] > \$second &&                \$arr[\$i] != \$first)            \$second = \$arr[\$i];    }    if (\$second == PHP_INT_MIN)        echo("There is no second largest element\n");    else        echo("The second largest element is "                 . \$second . "\n");}  // Driver Code\$arr = array(12, 35, 1, 10, 34, 1);\$n = sizeof(\$arr);print2largest(\$arr, \$n);  ?>
Output
The second largest element is 34

My Personal Notes arrow_drop_up