Search code examples
phpalgorithmsortingquicksort

Quick Sort in PHP


I have tried to implement the traditional approach of Quicksort of "C" in PHP. The way it is supposed to work it is not working in PHP. This logic works in C but not in PHP.

  • First processed the partition part
  • swap the pivot values with the $upper
  • use of quicksort function recursively

<?php
$array=array(7, 6, 5, 9, 2, 1, 15, 7);
$L=0;
$U=count($array)-1;
function Partition($a, $lower, $Upper)
{   
        $i=$lower;
        $j=$Upper;
        $pivot=$a[lower];

        while($i<$j)
        {

        while($a[$i]<$pivot)
        {
            $i++;
        }

        while($a[$j]>$pivot)
        {
            $j--;
        }

        if($i<$j)
        {
            $temp = $a[$i];
            $a[$i] = $a[$j];
            $a[$j] = $temp;
        }
        $i++;
        }
        $a[$lower]=$a[$j];
        $a[$j]=$pivot;

        return $j;
}
function QuickSort($a, $lower, $Upper)
{
    if($lower<$Upper)
    {
        $loc= Partition($a, $lower, $Upper);
        QuickSort($a, $lower, $loc-1);
        QuickSort($a, $loc+1, $Upper);
    }
    print_r($a);
}
QuickSort($array, $L, $U);
print_r($array);


Solution

  • Arrays are not passed by reference by default in PHP. (They're not simply pointers like they would be in C.) So your functions aren't actually changing the input array.

    I've modified your function declarations below and it now works as expected.

    Also, you need $pivot=$a[lower] to be $pivot=$a[$lower];;

    <?php
    $array=array(7, 6, 5, 9, 2, 1, 15, 7);
    $L=0;
    $U=count($array)-1;
    function Partition(&$a, $lower, $Upper)
    {   
            $i=$lower;
            $j=$Upper;
            $pivot=$a[$lower];
    
            while($i<$j)
            {
    
            while($a[$i]<$pivot)
            {
                $i++;
            }
    
            while($a[$j]>$pivot)
            {
                $j--;
            }
    
            if($i<$j)
            {
                $temp = $a[$i];
                $a[$i] = $a[$j];
                $a[$j] = $temp;
            }
            $i++;
            }
            $a[$lower]=$a[$j];
            $a[$j]=$pivot;
    
            return $j;
    }
    function QuickSort(&$a, $lower, $Upper)
    {
        if($lower<$Upper)
        {
            $loc= Partition($a, $lower, $Upper);
            QuickSort($a, $lower, $loc-1);
            QuickSort($a, $loc+1, $Upper);
        }
        print_r($a);
    }
    QuickSort($array, $L, $U);
    print_r($array);
    

    It's worth noting that the sort functions for arrays that PHP provides already use an implementation of QuickSort.