I was asked this in the test for a job yesterday, and i ended up using count sort. I failed coz it uses many for loops and it iterates the array more than once. Any one can help..
$data = array(1,9,23,7,6,10,12,111);
$x1 = $data[0];
$x2 = $data[1];
for ($i = 2; $i < count($data); $i++)
{
if ($data[$i] > $x2 && $x2 < $x1) {
$x2 = $data[$i];
} elseif ($data[$i] > $x1 && $x1 < $x2) {
$x1 = $data[$i];
}
}
var_dump($x1, $x2);
Its giving me largest element
$array=array(2,3,11,6,4,7);
$max=$array[0];
foreach($array as $d)
{
if($d > $max){
$max=$d;
}
}
echo $max;
EDIT: This is revised removing the arsort()
I originally used which, as pointed out, is a native PHP function. This script will account for random orders of unknown values meaning you can assign $a
as any range of numbers in any order and it will still grab the top 2.
// create array
$a = range(1,20);
// Shuffle so it's random order
shuffle($a);
// Start at 0 for each comparison
$val1 = 0;
$val2 = 0;
// loop through
foreach($a as $values) {
// If current $values is greater than at least
// one of the stored $val1 & $val2
if(($values > $val1) || ($values > $val2)) {
// Check which is greater of two stored
if($val1 > $val2)
// Assign val2 if val1 is greater
// You need to replace the smaller
// of the two values
$val2 = $values;
else
// Opposite of above
$val1 = $values;
}
}
// voila! reveal top 2
var_dump($val1,$val2);
This will give you either 20 19
or 19 20
, depending on the order of the shuffled array.