views:

364

answers:

4

I got the following php function, and want to change it into descending sorting, can someone help me:

function quickSort(&$numbers, $array_size,$level)
{
   q_sort($numbers, 0, $array_size - 1,$level);
}


function q_sort(&$numbers, $left, $right,$level)
{
   $l_hold = $left;
   $r_hold = $right;
   $pivot = $numbers[$left];


   while ($left < $right)
   {
      if ($level == 'RegID')
      {
         while (($numbers[$right]->RegID >= $pivot->RegID) && ($left < $right))
            $right--;
      }


      if ($left != $right)
      {
         $numbers[$left] = $numbers[$right];
         $left++;
      }

      if($level == 'RegID')
      {
         while (($numbers[$left]->RegID >= $pivot->RegID) && ($left < $right))
            $left++;
      }



      if ($left != $right)
      {
         $numbers[$right] = $numbers[$left];
         $right--;
      }
   }

   $numbers[$left] = $pivot;
   $pivot = $left;
   $left = $l_hold;
   $right = $r_hold;

   if ($left < $pivot)
      q_sort($numbers, $left, $pivot-1,$level);
   if ($right > $pivot)
      q_sort($numbers, $pivot+1, $right,$level);

}
+1  A: 

Simple: whenever you're comparing elements, change a '>' to a '<' and vice versa.

This works for all sorting algorithms and any kind of ordering: replace any comparison of elements of the array by any expression answering the question of one element should precede the other in the sorted array.

Martijn
+2  A: 

Of course it is. Just look how the algorithm works.

  if ($level == 'RegID')
  {
     // Comparison
     while (($numbers[$right]->RegID >= $pivot->RegID) && ($left < $right))
        $right--;

  }


  if ($left != $right)
  {
     $numbers[$left] = $numbers[$right];
     $left++;
  }

  if($level == 'RegID')
  {
     // Comparison
     while (($numbers[$left]->RegID >= $pivot->RegID) && ($left < $right))
        $left++;
  }

You will just have to change the way the algorithm decides whether one element is greater than another - Hence you must change the comparison operator from >= to <.

Note: Can't you just use a builtin sort function?

Dario
+1 for the note, too! Why write it yourself?
xtofl
A: 

The 'generic' way would be to provide a comparison function (object), something like

function q_sort( &$numbers, $left, $right,$level, $comparison )
{
...
    if( $comparison->ordered( $left, $right ) )
    {...
    }
}
xtofl
A: 

Don't write your own sort function, use one of the builtins:

function cmp($a, $b) {
        return a->RegID - b->RegID;
}
uasort($a, "cmp");