Skip to content
Advertisement

Sort array into alternating smallest largest values?

Does anyone know how to sort an array into alternating smallest largest values?

I.E.

Array (10, 2, 5, 1, 30, 1, 7)

Should be :

(30, 1, 10, 1, 7, 2, 5)

EDIT:

Forgot to mention the arrays are associative, so:

Array("A"=>10, "B"=>2, "C"=>5, "D"=>1, "E"=>30, "F"=>1, "G"=>7)

Should become:

("E"=>30, "D"=>1, "A"=>10, "F"=>1, "G"=>7, "B"=>2, "C"=>5)

Advertisement

Answer

Sort your array then push elements from beginning and end of the array alternatively:

<?php

    $myArray = array(10, 2, 5, 1, 30, 1, 7);
    sort($myArray );
    $count=sizeof($myArray );

    $result= array();
    
    for($counter=0; $counter * 2 < $count; $counter++){

         array_push($result, $myArray[$count - $counter - 1]);
         //check if same elements (when the count is odd)
         if ($counter != $count - $counter - 1) {
             array_push($result, $myArray[$counter]);
         }

    }
    print_r ($result);

?>

returns:

Array ( [0] => 30 [1] => 1 [2] => 10 [3] => 1 [4] => 7 [5] => 2 [6] => 5 )
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement