简体   繁体   中英

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?

This could be nice for other functions too where is just an IF comparison what's changes

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.

In this case you could multiply both operands with -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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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