[php] 数据结构&算法(PHP描述) 快速排序 quick sort
1 <?php 2 /** 3 * 快速排序 quick sort 4 * 5 **/ 6 7 function sort_quick($arrData) { 8 if(empty($arrData) || !is_array($arrData)) return false; 9 10 $flag = $arrData[0]; 11 $len = count($arrData) - 1; 12 if($len == 0) return $arrData; // 如果只有一个数据的数组直接返回 13 14 $arrLeft = array(); 15 $arrRight = array(); 16 $len_l = 0; 17 $len_r = 0; 18 for($i = 1; $i <= $len;$i++) { 19 if($arrData[$i] < $flag) { 20 $arrLeft[$len_l] = $arrData[$i]; // 小于的放左边 21 $len_l++; 22 } else { 23 $arrRight[$len_r] = $arrData[$i]; // 大于等于的放右边 24 $len_r++; 25 } 26 } 27 28 // 合并数组 29 $arrResult = array(); 30 if($len_l) { 31 $arrLeft = sort_quick($arrLeft); 32 for($i = 0;$i <= $len_l - 1; $i++ ) { 33 $arrResult[$i] = $arrLeft[$i]; 34 } 35 } 36 $arrResult[$len_l] = $flag; 37 $len_l++; 38 if($len_r) { 39 $arrRight = sort_quick($arrRight); 40 for($i = 0;$i <= $len_r - 1; $i++ ) { 41 $arrResult[$len_l] = $arrRight[$i]; 42 $len_l++; 43 } 44 } 45 echo "== ",$flag," ==========================================<br/>"; 46 echo "data : ",print_r($arrData),"<br/>"; 47 echo "filter left: ",print_r($arrLeft),"<br/>"; 48 echo "filter right: ",print_r($arrRight),"<br/>"; 49 echo "return : ",print_r($arrResult),"<br/>"; 50 51 return $arrResult; 52 } 53 //$list = array(4,3,2,1,5,7,3,7); 54 $list = array(4,51,6,73,2,5,9,33,50,3,4,6,1,4,67); 55 $list = sort_quick($list); 56 echo "<pre>";print_r($list);
think in coding