Search code examples
phpbubble-sort

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


Solution

  • 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.