note 12520 deleted from function.sort by derick

From: Date: Wed, 31 Aug 2005 10:36:35 +0000
Subject: note 12520 deleted from function.sort by derick
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-94491@lists.php.net to get a copy of this message
Note Submitter: Richard dot C dot Mitchell at Boeing dot com ---- I found an error in the qsort_multiarray() function posted above. The last argument ($right) should have a default value less than -1, because -1 can occur in a recursive call to the function. I have re-written (and renamed) the function to fix that problem and to make it more efficient. I also renamed the variables and added comments. ----------------------- cut here ----------------------- <?php // filename: qsort2.php function array_qsort2 (&$array, $column=0, $order=SORT_ASC, $first=0, $last= -2) { // $array - the array to be sorted // $column - index (column) on which to sort // can be a string if using an associative array // $order - SORT_ASC (default) for ascending or SORT_DESC for descending // $first - start index (row) for partial array sort // $last - stop index (row) for partial array sort if($last == -2) $last = count($array) - 1; if($last > $first) { $alpha = $first; $omega = $last; $guess = $array[$alpha][$column]; while($omega >= $alpha) { if($order == SORT_ASC) { while($array[$alpha][$column] < $guess) $alpha++; while($array[$omega][$column] > $guess) $omega--; } else { while($array[$alpha][$column] > $guess) $alpha++; while($array[$omega][$column] < $guess) $omega--; } if($alpha > $omega) break; $temporary = $array[$alpha]; $array[$alpha++] = $array[$omega]; $array[$omega--] = $temporary; } array_qsort2 ($array, $column, $order, $first, $omega); array_qsort2 ($array, $column, $order, $alpha, $last); } } ?> ----------------------- cut here ----------------------- <?php // filename: qtest1.php require_once("qsort2.php"); $cat = Array( Array( 1,3 ), Array( 0,6 ), Array( 5,2 ), Array( 8,4 ), ); print "<pre>"; print_r($cat); array_qsort2 ($cat, 1, SORT_DESC); print_r($cat); print "</pre>"; ?> ----------------------- cut here ----------------------- <?php // filename: qtest2.php require_once("qsort2.php"); $numbers = Array( Array ( "number"=>1, "english"=>"one", "spanish"=>"uno" ), Array ( "number"=>2, "english"=>"two", "spanish"=>"dos" ), Array ( "number"=>3, "english"=>"three", "spanish"=>"tres" ), Array ( "number"=>4, "english"=>"four", "spanish"=>"cuatro" ), Array ( "number"=>5, "english"=>"five", "spanish"=>"cinco" ), ); print "<pre>"; print_r($numbers); array_qsort2 ($numbers, "spanish"); print_r($numbers); print "</pre>"; ?> ----------------------- cut here -----------------------

« previous php.notes (#94491) next »