Write a PHP code to find second largest number in array. Given an unsorted array, we have to write a PHP program to find the second largest number in an array.
Apart from solving this problem. We have to focus on time complexity. As the time complexity of an algorithm is very important in terms of how efficient your algorithm is.
For example – Let’s take an array.
Input – arr[] = { 4, 9, 5, 2, 8, 0, 3, 22}
Output – 9
The second largest element in this array is 9.
We have discussed the problem statement. Let’s think, how we can solve this problem efficiently? There are multiple ways to solve this problem. Which approach you prefer and why?
How to Find Second Largest Number in Array – PHP Code
Approach 1:
One approach is to sort an array. PHP provides several functions for sorting an array. After sorting, pick the element present at n-2 position where n is the size of an array.
The time complexity of this approach is O(nlogn).
1 2 3 4 5 6 7 8 9 |
function secondHighest(array $arr) { sort($arr); echo $arr[sizeof($arr)-2]; } secondHighest(array( 4, 9, 5, 2, 8, 0, 3, 22)); |
NOTE: If the element of an array is repeated then this approach won’t work.
To understand this concept, let’s take an example.
int num[] = {1, 9, 5, 55, 8, -1, 3, 55};
So what will be the second highest number if we use above method (sort and pick the element present at n-2 index). The element is 55 which is wrong.
Approach 2:
Traverse an array and maintain two indexes max and second max. The code for this approach is written below.
PHP Code to Find Second Largest Number in an Array
The idea here is to find the second largest number using single loop. To do that, declare two variables max and secondMax. Initially, Assign them with Integer minimum possible value (In PHP, we can do that by using PHP_INT_MIN).
In each iteration, Compare the value present at current index with max and secondMax variable. If current value is greater than the max then assign max value in secondMax and current value in max variable.
The time complexity of this approach is O(n).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
/** * * @param array $arr * @return second highest number of an array */ function findSecondMax(array $arr) { //If array is empty then return if(empty($arr)) { return; } /* * Initialize max and second max with negative value */ $max = PHP_INT_MIN; $secondMax = PHP_INT_MIN; //Traverse an array foreach($arr as $number) { //If it's greater than the value of max if($number > $max) { $secondMax = $max; $max = $number; } //If array number is greater than secondMax and less than max if($number > $secondMax && $number < $max) { $secondMax = $number; } } return $secondMax; } $arr = array(70, 4, 8, 10, 14, 9, 7, 6, 5, 3, 2); $second_maximum = findSecondMax($arr); echo "Second Highest Element is ".$second_maximum; |