2012-07-03 82 views
0

我在做一个气泡排序函数并遇到可变的运算符问题。开始处有一个开关块,用于确定是按升序还是降序排序。 如果条件存在,$运算符将用于以下条件。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

欢迎来到Stack Overflow。你有什么问题?出了什么问题? – Utkanos

回答

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,而忽略了在函数的第一行。

+0

非常感谢。这个解决方案让我知道另一种编写代码的方式。 “if(($ ascending &&($ arr [$ j]> $ arr [$ j + 1]))||(!$ ascending &&($ arr [$ j] <$ arr [$ j + 1])) “可能对未来的某些情况有用,这确实使用了PHP的&&和||特性 –