【问题标题】:Variable operator in if conditionif条件下的变量运算符
【发布时间】:2012-07-03 09:42:54
【问题描述】:

我在做一个冒泡排序函数,遇到一个变量操作符问题。开头有一个switch块来决定是升序还是降序排序。 $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);
?>

【问题讨论】:

  • 欢迎来到 Stack Overflow。你有什么问题?怎么了?

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


【解决方案1】:

虽然从技术上讲,可以将运算符(&lt;&gt;)放在一个字符串中并从中编译出一个表达式(使用 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,省略函数中的第一行。

【讨论】:

  • 非常感谢。这个解决方案让我知道了另一种编写代码的方法。 "如果 (($ascending && ($arr[$j] > $arr[$j+1])) || (!$ascending && ($arr[$j]
猜你喜欢
  • 2022-10-15
  • 1970-01-01
  • 2012-03-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-04
  • 2017-03-21
  • 2015-10-06
  • 2014-12-11
相关资源
最近更新 更多