Search code examples
phpvariablessortingoperator-keywordbubble-sort

Variable operator in if condition


I am doing a bubble sort function and encounter a variable operator problem. There is a switch block at the beginning to determine whether it should be sorted in ascending or descending order. The $operator is intended to be used in the following if condition.


<?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);
?>

Solution

  • While technically it is possible to put the operator (< or >) in a string and compile an expression out of it (using eval()), most of the time you neither need nor want this. Simply assigning a boolean that decides whether to sort ascending, and then evaluating that boolean is a more common way to go.

    Your code then comes down to something like this:

    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;
    }
    

    Of course you can skip the string evaluation and change the $operation="ascending" parameter to $ascending = true, leaving out the first line in the function.