在不使用php内置函数的情况下,将每5个数字数组的排序从升序更改为降序,反之亦然



下面有一个数组编号,

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

预期输出必须为:

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

排序必须每隔5个数组从升序变为降序,反之亦然。因此,如果前5位按升序排序,则后5位必须按降序排序,依此类推

但我得到了:

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

在我的代码下面:

$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));

使用PHP内置函数绝对有帮助:

/**
* @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(&quot-5,-3,-2,-1,1,20,12,9,8,7,2,4,5,6";

我想这就是你想要的。我们将数组分为5组,然后一次分组一个,先从前面分组,然后从后面分组,重复这种模式。如果我们从后面取,那么我们也需要反向排序。


$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);

此处演示:https://3v4l.org/KGgWI

最新更新