简体   繁体   English

气泡排序和订单类型

[英]Bubble Sort and order type

I was working on a bubble sort(In PHP) and I wanted to add an extra parameter to my function, where it decides order type (Low to High or High to Low), so instead of copy paste all the code and just change one sign, is there something like a special sintaxys or anything I can add to? 我当时在进行冒泡排序(在PHP中),我想在函数中添加一个额外的参数,该参数决定顺序类型(从低到高或从高到低),因此与其复制粘贴所有代码,而只需更改一个代码标志,是否有类似特殊的sintaxys或我可以添加的内容?

This could be nice for other functions too where is just an IF comparison what's changes 这对于其他功能也可能很好,这只是一个IF比较

function bubbleSort($array,$order){
$cnt = count($array);
if($cnt > 0) {
    for ($i = 0; $i < $cnt; $i++) {
        for ($j = 0; $j < $cnt - 1 - ($i); $j++) {
            $temp = $array[$j];
            if ($array[$j] ***>*** $array[$j + 1]) { // Here is where that sign must change
                $array[$j] = $array[$j + 1];
                $array[$j + 1] = $temp;
            }
        }
    }
}
return $array;

} }

I know the title of the question is not that clever. 我知道问题的标题不是那么聪明。 I appreciatte your time and help 我感谢您的时间和帮助

You can add a negative sign in front of the elements to be checked so that the reverse happens. 您可以在要检查的元素前面添加一个负号,以便进行相反的操作。

Multiplying the elements (wherever you are checking inequality) by $c where $c is +1 or -1 as per High to Low or Low to High. 将元素(无论您在哪里检查不平等)乘以$c ,其中$c是+1或-1(根据从高到低或从低到高的顺序)。

In this case you could multiply both operands with -1: 在这种情况下,您可以将两个操作数都乘以-1:

const LOW_TO_HIGH = 1;
const HIGH_TO_LOW = -1;

function bubbleSort($array,$order){
    $cnt = count($array);
    if($cnt > 0) {
        for ($i = 0; $i < $cnt; $i++) {
            for ($j = 0; $j < $cnt - 1 - ($i); $j++) {
                $temp = $array[$j];
                if ($array[$j] * $order > $array[$j + 1] * $order) { 
                    $array[$j] = $array[$j + 1];
                    $array[$j + 1] = $temp;
                }
            }
        }
    }
    return $array;
}

Then you pass one of these two constants to bubbleSort as second parameter. 然后,将这两个常量之一作为第二个参数传递给bubbleSort。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM