Write a program to get second highest number in an array using PHP ?
Given an array of integers, 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 18 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
function bubbleSort(&$arr) {
$n = sizeof($arr);
// Traverse through all array elements
for($i = 0; $i < $n; $i++) {
$swapped = False;
// Last i elements are already
// in place
for ($j = 0; $j < $n - $i - 1; $j++) {
// traverse the array from 0 to
// n-i-1. Swap if the element
// found is greater than the
// next element
if ($arr[$j] <$arr[$j+1]) {
$t = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $t;
$swapped = True;
}
}
// IF no two elements were swapped
// by inner loop, then break
if ($swapped == False)
break;
}
}
// Driver code to test above
$arr = array(64, 34, 25, 12, 22, 11, 90);
$len = sizeof($arr);
bubbleSort($arr);
if($arr[0] == $arr[1]) {
echo "No element";
}
else {
echo "Second Largest element is ".$arr[1];
}
?>
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[0] element)
2) Start traversing the array from array[1],
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
// PHP program to find second largest
// element in an array
// Function to print the
// second largest elements
function print2largest($arr, $arr_size) {
// There should be atleast
// two elements
if ($arr_size < 2) {
echo(" Invalid Input ");
return;
}
$first = $second = PHP_INT_MIN;
for ($i = 0; $i < $arr_size ; $i++) {
// If current element is
// smaller than first
// then update both
// first and second
if ($arr[$i] > $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
Another Approach: Sort the array in descending order using the PHP rsort() method and then return the second element from the sorted array. Here, we have declared a returnSecondHighest() method that accepts an array. By implementing the rsort() method in PHP that will sort the array in descending order. Now, store the second-highest element of the sorted array by using the 1st index of the array in a variable. Here, we declare the user-defined array of numbers & call the returnSecondHighest() method and print the second-highest element of the array.
PHP Code:
<?php
function returnSecondHighest(array $myarray){
// Sort the array in descending order
rsort($myarray);
// Save the element from the second last position of sorted array
$secondHighest = $myarray[1];
// Return second highest number
return $secondHighest;
}
// Driver code to test above
$arr = array(64, 34, 25, 12, 22, 11, 90);
// Call the function and print output
echo "Second highest number : ".returnSecondHighest($arr);
?>
Output: The time complexity of this program is O(nlogn) as the PHP rsort() method takes O(nlogn) where n is the number of elements in the array parameter.
Second highest number : 64
Using Max Function with Filter
To find the second highest number in an array in PHP using the Max Function with Filter approach, apply max() to an array filtered to exclude the maximum value. Then, retrieve the maximum value from the filtered array, which represents the second highest number.
Example:
<?php
function returnSecondHighest(array $myarray) {
// Find the maximum value in the array
$max_value = max($myarray);
// Filter out the maximum value to find the new maximum (second highest)
$filtered_array = array_filter($myarray, function($value) use ($max_value) {
return $value < $max_value;
});
// Find the second highest value in the filtered array
$secondHighest = max($filtered_array);
// Return the second highest number
return $secondHighest;
}
// Driver code to test above
$arr = array(64, 34, 25, 12, 22, 11, 90);
// Call the function and print output
echo "Second highest number : " . returnSecondHighest($arr);
?>
Output:
Second highest number : 64
Using Set to Remove Duplicates
This method involves converting the array into a set to remove duplicates, then finding the largest and second-largest values by iterating through the set.
Example: In this example, the findSecondLargest function first removes duplicates from the array using array_unique and array_values. It then checks if there are fewer than two unique elements, in which case it returns a message indicating that the second largest does not exist. Otherwise, it initializes the first and second largest elements to PHP_INT_MIN and traverses the unique array to find the largest and second-largest elements.
<?php
function findSecondLargest($array) {
// Remove duplicates by converting the array to a set
$uniqueArray = array_values(array_unique($array));
// Check if the array has fewer than 2 unique elements
if (count($uniqueArray) < 2) {
return "The second largest does not exist.";
}
// Initialize first and second largest
$first = $second = PHP_INT_MIN;
// Traverse the array to find the first and second largest elements
foreach ($uniqueArray as $element) {
if ($element > $first) {
$second = $first;
$first = $element;
} elseif ($element > $second) {
$second = $element;
}
}
return $second;
}
// Example usage
$arr1 = [13, 14, 15, 16, 17, 18];
echo "The second largest element is " . findSecondLargest($arr1) . "\n";
// Output: The second largest element is 17
$arr2 = [10, 5, 10];
echo "The second largest element is " . findSecondLargest($arr2) . "\n";
// Output: The second largest element is 5
$arr3 = [10, 10, 10];
echo "The second largest element is " . findSecondLargest($arr3) . "\n";
// Output: The second largest does not exist.
?>
Output
The second largest element is 17 The second largest element is 5 The second largest element is The second largest does not exist.
Using Two Passe
This method involves making two passes through the array. In the first pass, you find the maximum element. In the second pass, you find the largest element that is not equal to the maximum element. This approach ensures that you efficiently find the second largest element without sorting or using additional data structures.
Example: This approach is simple and efficient, requiring only two passes through the array. It avoids sorting the array or using complex data structures while ensuring the correct result is found.
<?php
function findSecondLargestTwoPasses($array) {
if (count($array) < 2) {
return "The second largest element does not exist.";
}
// First pass to find the maximum element
$max = max($array);
// Second pass to find the largest element that is not equal to the maximum element
$secondMax = PHP_INT_MIN;
foreach ($array as $value) {
if ($value != $max && $value > $secondMax) {
$secondMax = $value;
}
}
// Check if the second largest element exists
if ($secondMax == PHP_INT_MIN) {
return "The second largest element does not exist.";
}
return $secondMax;
}
// Example usage:
$array = [13, 14, 15, 16, 17, 18];
echo "The second largest element is " . findSecondLargestTwoPasses($array) . "\n";
$array = [10, 5, 10];
echo "The second largest element is " . findSecondLargestTwoPasses($array) . "\n";
$array = [10, 10, 10];
echo findSecondLargestTwoPasses($array) . "\n";
?>
Output
The second largest element is 17 The second largest element is 5 The second largest element does not exist.
Using a Heap Data Structure
To find the second largest element efficiently, you can use a max-heap data structure. This approach is particularly useful when dealing with large datasets.
Example: In this example we use a max heap to find the second largest element in an array. It inserts array elements into the heap, extracts the largest, then finds and returns the second largest.
<?php
function findSecondLargestWithHeap($arr) {
if (count($arr) < 2) {
return "The second largest element does not exist.";
}
// Create a max heap from the array
$maxHeap = new SplMaxHeap();
foreach ($arr as $value) {
$maxHeap->insert($value);
}
// Extract the largest element
$first = $maxHeap->extract();
// Extract the second largest element
while (!$maxHeap->isEmpty()) {
$second = $maxHeap->extract();
if ($second < $first) {
return "The second largest element is $second";
}
}
return "The second largest element does not exist.";
}
$arr = [13, 14, 15, 16, 17, 18];
echo findSecondLargestWithHeap($arr);
?>
Output
The second largest element is 17