码迷,mamicode.com
首页 > 其他好文 > 详细

Quick Sort

时间:2014-11-09 19:29:28      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   sp   for   div   

 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

标签:style   blog   io   color   ar   os   sp   for   div   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!