首页 > 代码库 > Quick Sort

Quick Sort

 1 <?php 2 function sortQuick($a) 3 { 4     // find array size 5     $length = count($a); 6      7     // base case test, if array of length 0 then just return array to caller 8     if($length < 2){ 9         return $a;10     }11     12     // select an item to act as our pivot point, since list is unsorted first position is easiest13     $pivot = $a[0];14     15     // declare our two arrays to act as partitions16     $left = $right = array();17     18     // loop and compare each item in the array to the pivot value, place item in appropriate partition19     for($i = 1; $i < $length; $i++)20     {21         if($a[$i] < $pivot){22             $left[] = $a[$i];23         }24         else{25             $right[] = $a[$i];26         }27     }28     29     // use recursion to now sort the left and right lists30     return array_merge(sortQuick($left), array($pivot), sortQuick($right));31 }32 33 $unsorted = array(9, 5, 2, 7, 3);34 $sorted = sortQuick($unsorted);35 echo implode(‘, ‘, $sorted);36 37 // 2, 3, 5, 7, 938 ?>

 

Quick Sort