简体   繁体   中英

how to find highest and second highest number in an array without using max function

I already have solution. But i think it will be more optimizable. So please provide me a solution for it. And remember that don't use predefined function of php. Like max() function. i know there are so many ways to find it but i want best and better solution. Because my array contains more than 1 lakh records and it's taking lot of time. Or sometime site will be down.

My code:

<?php 

$array = array('1', '15', '2','10',4);

echo "<pre>";
print_r($array);
echo "<pre>";
$max = 0;
$s_max=0;

for($i=0; $i<count($array); $i++)
{
    $a = $array[$i];
    $tmax = $max;
    $ts_max = $s_max;
    if($a > $tmax && $a > $ts_max)
    {
        $max = $a;
        if($tmax > $ts_max) {
            $s_max = $tmax;
        } else {
            $s_max = $ts_max;
        }
    } else if($tmax > $a && $tmax > $ts_max)
    {
        $max = $tmax;
        if($a > $ts_max) {
            $s_max = $a;
        } else {
            $s_max = $ts_max;
        }
    } else if($ts_max > $a && $ts_max > $tmax)
    {
        $max = $ts_max;
        if($a > $tmax)
        {
            $s_max = $a;
        } else {
            $s_max = $tmax;
        }
    }
}
echo "Max=".$max;
    echo "<br />";
    echo "S_max=".$s_max;
    echo "<br />";

?>
<?php 
$array = array('200', '15','69','122','50','201');
$max_1 = $max_2 = 0;

for ($i=0; $i<count($array); $i++) {
    if ($array[$i] > $max_1) {
      $max_2 = $max_1;
      $max_1 = $array[$i];
    } else if ($array[$i] > $max_2 && $array[$i] != $max) {
      $max_2 = $array[$i];
    }
}
echo "Max=".$max_1;
echo "<br />"; 
echo "Smax 2=".$max_2;

See this solution.

<?php 

 $numbers = array_unique(array(1,15,2,10,4)); 
// rsort : sorts an array in reverse order (highest to lowest).

 rsort($numbers); 

 echo 'Highest is -'.$numbers[0].', Second highest is -'.$numbers[1];

 // O/P: Highest is -15, Second highest is -10
 ?>

I didn't check your solution, but in terms of complexity it's IMO optimal. If the array has no more structural information (like it's sorted) there's no way to skip entries. Ie the best solution is in O(n) which your solution is.

This is a perfect and shortest code to find out the second largest value from the array. The below code will always return values in case the array contains only a value.

Example 1.
    $arr = [5, 8, 1, 9, 24, 14, 36, 25, 78, 15, 37];
    asort($arr);
    $secondLargestVal = $arr[count($arr)-1];

    //this will return 37

Example 2.

    $arr = [5];
    asort($arr);
    $secondLargestVal = $arr[count($arr)-1];
    //this will return 5

The answer given by "Kanishka Panamaldeniya" is fine for highest value but will fail on second highest value ie if array has 2-similar highest value, then it will showing both Highest and second highest value same. I have sorted out it by adding one more level comparsion and it works fine.

$array = array(50,250,30,250,40,70,10,50); // 250  2-times
$max=$max2=0;
for ($i = 0; $i < count($array); $i++) {
if ($array[$i] > $max) {
    $max2 = $max;
    $max = $array[$i];
} else if (($array[$i] > $max2) && ($array[$i] != $max)) {
    $max2 = $array[$i];
}
}
echo "Highest Value is : " . $max . "<br/>"; //output : 250
echo "Second highest value is : " . $max2 . "<br/>"; //output : 70

This code will return second max value from array

$array = array(80,250,30,250,40,90,10,50,60,50); // 250  2-times
$max=$max2=0;

for ($i = 0; $i < count($array); $i++) {
    if($i == 0) {
        $max2 = $array[$i];
    }
     
    if($array[$i] > $max) {
        $max = $array[$i];
    }
    
    if($max > $array[$i] && $array[$i] > $max2) {
        $max2 = $array[$i];
    }
}    


echo "Highest Value is : " . $max . "<br/>"; //output : 250
echo "Second highest value is : " . $max2 . "<br/>"; //output : 90
$array = array(80,250,30,40,90,10,50,60,50);            // 250  2-times
$max=$max2=0;

foreach ($array as $key =>$val) {

    if($max < $val) {
        $max2 =$max;
        $max = $val;        
    }

    elseif(($max2 < $val) && ($max!=$val) {
        $max2 = $val;
    }
}

echo "Highest Value is : " . $max . "<br/>";           //output: 250
echo "Second highest value is : " . $max2 . "<br/>";   //output: 90

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在此处输入图片说明

See this solution, PHP find second largest element in given array without built-in sort function

<?php

function secondLargest($array){
    for($i=0; $i<count($array); $i++){
        for($j=0; $j<count($array)-1; $j++){
            if($array[$j] > $array[$j+1]){
            $temp = $array[$j+1];
            $array[$j+1] = $array[$j];
            $array[$j] = $temp;
            }
        }
    }
  return $array[sizeof($array)-2];
}

$arr = [-1, 8, 4, 2, 8];
print_r(secondLargest($arr));
?>

Two way find the second highest salary 
1. Sort the data in Descending order
2. get array first value
3. Check the condition already comments

$array =  [2,3,6,11,17,14,19];
$max   =  $array[0];
$count =  count($array);
for($i=0; $i<$count;$i++)
{
      for($j=$i+1;$j<$count;$j++)
      {
         if($array[$i] < $array[$j])
         {
            $temp = $array[$i];
            $array[$i] = $array[$j];
            $array[$j] = $temp;
         }
      }
}

First Method
//echo $array[1]; // Second highest value

$second ='';
for($k=0;$k<2;$k++)
{
    if($array[$k] >$max)
    {
        $second = $array[$k];       
    }
}
echo $second; // Second method

Without using MAX function. Here.

$arr = [3,4,-5,-3,1,0,4,4,4];
rsort($arr); // SORT ARRAY IN DESCENDING ORDER

$largest = $arr[0]; // IN DESCENDING ORDER THE LARGEST ELEMENT IS ALWAYS THE FIRST ELEMENT

$secondLargest = 0;

foreach($arr as $val){
    $secondLargest = $val; // KEEP UPDATING THE VARIABLE WITH THE VALUE UNTIL IT RECEIVES THE FIRST ELEMENT WHICH IS DIFFERENT FROM THE LARGEST VALUE
    
    if($val != $arr[0]){
        break; // BREAK OUT OF THE LOOP AS SOON AS THE VALUE IS DIFFERENT THAN THE LARGEST ELEMENT
    }
}

echo $secondLargest;

This code treats repeated values as one, ie "43" presented twice, but next value is "24".

$ar = [2, 3, 24, 5, 4, 5, 43, 43, 23];
$max = null;
$maxNext = null; 

foreach ($ar as $value) {
    if ($max === null || $value > $max) {
        $maxNext = $max;
        $max = $value;
    }
}

var_dump($max, $maxNext); // 43, 24

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM