You can also use techniques in sorting like Bubble sort
function bubble_Sort[$my_array ]
{
do
{
$swapped = false;
for[ $i = 0, $c = count[ $my_array ] - 1; $i < $c; $i++ ]
{
if[ $my_array[$i] > $my_array[$i + 1] ]
{
list[ $my_array[$i + 1], $my_array[$i] ] =
array[ $my_array[$i], $my_array[$i + 1] ];
$swapped = true;
}
}
}
while[ $swapped ];
return $my_array;
}
$test_array = array[3, 0, 2, 5, -1, 4, 1];
echo "Original Array :\n";
echo implode[', ',$test_array ];
echo "\nSorted Array\n:";
echo implode[', ',bubble_Sort[$test_array]]. PHP_EOL;
Original Array :
3, 0, 2, 5, -1, 4, 1
Sorted Array :
-1, 0, 1, 2, 3, 4, 5
Flow explanation
Problem:- Find the Second Largest Number in an Array Using PHP?, how to find highest and second highest number in an array without function, Find the second highest variable in array, Find Second largest element in an array
Solution – Find the Second Largest Number in an Array Using PHP
Related Articles
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[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
Output
The second largest element is 34