if条件下的变量运算符

时间:2012-07-03 09:42:54

标签: php variables sorting operator-keyword bubble-sort

我正在进行冒泡排序功能并遇到变量操作符问题。开头有一个开关块,用于确定是否应按升序或降序排序。 $运算符旨在用于以下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);
?>

1 个答案:

答案 0 :(得分:3)

虽然从技术上讲,可以将操作符(<>)放在一个字符串中并从中编译表达式(使用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,而不会删除函数中的第一行。

相关问题