0

So I tried to reproduce the sorting algorithm "Cocktail Shaker Sort" in PHP, but could not proceed because I get the error:

"Undefined offset" and then some random number.

I am still quite new to programming in PHP and if anyone could help me here is my code below! Thank you and have a nice Day!

<!doctype html>
<html>

<head>
<meta charset="UTF-8">
<title>CocktailShake</title>
</head>

<body>
    <?php
        global $array;
        global $arraySorted;



        $intMin = 0;
        $intMax = 50;
        $maxLength = 69;
        $array = array();
        for($i=0; $i < $maxLength; $i++)
        {   
            $array[$i] = mt_rand($intMin, $intMax);             
            echo $array[$i]." ";
        }

        $arraySorted = array();
        for($x=0;$x<$maxLength-1;$x++)
        {
            if($array[$x]>=$array[$x+1])
            {
                $temp = $array[$x+1];
                $arraySorted[$x] = $temp;
                $arraySorted[$x+1] = $array[$x];
            }
            else{

            }
        }
        echo "<br>"."HIER ".$arraySorted[3];
        echo "<br>"."arraySorted:";
        for($i=0;$i < $maxLength-1; $i++){
            echo $arraySorted[$i]." ";
        }
    ?>

</body>
</html>

1 Answers1

0

You need one more loop to sort all elements:

function cocktailSorting(&$a) {
    $n = count($a);
    $left = 0;
    $right = $n - 1;
    do {
        for ($i = $left; $i < $right; $i++) {
            if ($a[$i] > $a[$i + 1]) {
                list($a[$i], $a[$i + 1]) = array($a[$i + 1], $a[$i]);
            }
        }
        $right -= 1;
        for ($i = $right; $i > $left; $i--) {
            if ($a[$i] < $a[$i - 1]) {
                list($a[$i], $a[$i - 1]) = array($a[$i - 1], $a[$i]);
            }
        }
        $left += 1;
    } while ($left <= $right);
}


    global $array;
    global $arraySorted;
    $intMin = 0;
    $intMax = 50;
    $maxLength = 69;
    $array = array();
    for($i=0; $i < $maxLength; $i++)
    {   
        $array[$i] = mt_rand($intMin, $intMax);             
        echo $array[$i]." ";
    }
cocktailSorting($array);
echo var_dump($array);
Vladimir
  • 1,373
  • 8
  • 12