Friday, April 12, 2013

Find Nth Highest value in array without sorting in PHP

Find  Nth/ N th highest value from given array without using any sorting in PHP

$ar = array(23,56,87,12,98,85,24,54,99,100,1,4,5,2,76,37,92);

$n =      count($ar);  //5;

for($i = 0; $i < $n; $i++){
echo $a = max($ar);                          // Get the max value from array // get the Nth value from last loop
//echo "
"; print_r($ar);

$ar = array_flip($ar);                        // Flip the array
//print_r($ar); 
unset($ar[$a]);                                 // Unset the max value from array
//print_r($ar);
$ar = array_flip($ar);                        // Flip the array
echo "
"; echo "
";
}