我正在做一个气泡排序函数,遇到了一个变量运算符问题。开头有一个开关块,用于确定是否应按升序或降序排序。该$operator用于以下 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);
?>
虽然从技术上讲,可以将运算符(<
或>
)放在一个字符串中并从中编译一个表达式(使用eval()
),但大多数时候你既不需要也不想要这个。只需分配一个布尔值来决定是否升序排序,然后计算该布尔值是一种更常见的方法。
然后,您的代码可以归结为如下所示的内容:
function bubbleSort($arr, $operation="ascending"){
$ascending = ($operation == "ascending");
//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 (($ascending && ($arr[$j] > $arr[$j+1]))
|| (!$ascending && ($arr[$j] < $arr[$j+1])))
{
$temp = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $temp;
}
}
}
return $arr;
}
当然,您可以跳过字符串求值并将$operation="ascending"
参数更改为 $ascending = true
,省略函数中的第一行。