Home > Enterprise >  Change the sorting of every 5 array of number from ascending to descending and vice versa without us
Change the sorting of every 5 array of number from ascending to descending and vice versa without us

Time:12-03

I have an array number below,

$arr = [2,5,1,12,-5,4,-1,3,-3,20,8,7,-2,6,9]

The expected output must be:

-5,-3,-2,-1,1,20,12,9,8,7,2,3,4,5,6

The sorting must be change every 5 array of number from ascending to descending and vice versa. So, if the first 5 digits is sorted as ascending, the second 5 digits must be sorted as descending and so on.

But I got:

-5,-3,-2,-1,1,2,3,4,5,6,7,8,9,12,20

Below my code:

$arr = array(2,5,1,12,-5,4,-1,3,-3,20,8,7,-2,6,9);

function arr_sort($array) {
    // get the size of array
    $countArr = count($array);
    
    for ($i=0; $i<$countArr; $i  ) {
        for ($j=$i; $j<$countArr; $j  ) {
            if ($array[$i] > $array[$j]) {
                $temporary = $array[$i];
                $array[$i] = $array[$j];
                $array[$j] = $temporary;
            }
        }
    }
    
    // order ascending and descending
    $array = implode(',', $array);
    return $array;
}

print_r(arr_sort($arr));

CodePudding user response:

Using PHP built-in functions definitely help:

/**
 * @param int[] $numbers
 * @return int[]
 */
function arr_sort(array $numbers): array
{
    // Sort items in ascending order first
    sort($numbers, SORT_NUMERIC);

    $result = [];
    $fetch_lowest = true;

    // Process until the input array is empty
    while (count($numbers) !== 0) {
        if ($fetch_lowest) {
            // Extract the 5 lowest numbers and keep them into ascending order
            $extract = array_splice($numbers, 0, 5);
        } else {
            // Extract the 5 highest numbers and reverse items to descending order
            $extract = array_splice($numbers, -5, 5);
            $extract = array_reverse($extract);
        }

        // Save the extracted items and switch the highest/lowest flag
        $result = array_merge($result, $extract);
        $fetch_lowest = !$fetch_lowest;
    }

    return $result;
}

$input = [2,5,1,12,-5,4,-1,3,-3,20,8,7,-2,6,9];
$sorted = arr_sort($input);

var_dump(implode(',', $sorted));

string(35) "-5,-3,-2,-1,1,20,12,9,8,7,2,3,4,5,6"

CodePudding user response:

I think this is what you are going for. We chunk the array into groups of 5, then take a grouping one at a time, first from the front, then the back, repeating that pattern. If we take from the back, we then also need to sort it in reverse.


$arr = [2,5,1,12,-5,4,-1,3,-3,20,8,7,-2,6,9];
$a = $arr;
asort($a);

$a = array_chunk($a, 5);

$output = [];
$idx = 0;
while($a){
    if($idx   % 2){
        $b = array_pop($a);
        arsort($b);
    }else{
        $b = array_shift($a);
    }
    $output = array_merge($output, $b);
}

var_dump($output);

Demo here: https://3v4l.org/KGgWI

  • Related