首页 > 其他 > 详细

Quick Sort

时间:2014-11-09 19:26:30      阅读:245      评论:0      收藏:0      [点我收藏+]
 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 easiest
13     $pivot = $a[0];
14     
15     // declare our two arrays to act as partitions
16     $left = $right = array();
17     
18     // loop and compare each item in the array to the pivot value, place item in appropriate partition
19     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 lists
30     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, 9
38 ?>

 

Quick Sort

原文:http://www.cnblogs.com/crepesofwrath/p/4085628.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!