首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。