我正在做一个冒泡排序功能并遇到变量运算符问题。开头有一个switch块来决定是升序还是降序排序。$ 运算符旨在用于以下 if 条件。
<?php
//bubble sort in ascending/descending order
function bubbleSort($arr, $operation="ascending"){
switch ($operation){
case "ascending":
$operator = ">";
break;
case "descending":
$operator = "<";
break;
}
//each loop put the largest number to the top
for ($i=0; $i<count($arr)-1; $i++){
//compare adjacent numbers
for ($j=0; $j<count($arr)-1-$i; $j++){
//exchange the adjacent numbers that are arranged in undesired order
if ($arr[$j]>$arr[$j+1]){
$temp = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $temp;
}
}
}
return $arr;
}
$arr1 = array(1000,10,2,20,-1,-6,-8,0,101);
$arr1 = bubbleSort($arr1, "ascending");
print_r($arr1);
?>