PHP Code to Find Second Largest Number in Array

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).

 

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).

How to Sort String in PHP.

Programming video tutorials

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.