Another very advanced sorting algorithm, quick sort ... This algorithm is very efficient.
The idea of a quick sort is to find a split point, separate the original array into two parts, and the left side of the split point is smaller than it, and on its right is bigger than it. Then the two parts are recursively called to sort, and the whole sort is completed.
The most important step, of course, is to slice and then make a recursive call, repeating the above split operation until break. code example below,
<?PHP//find the split point and Exchange valuesfunctionSlicearr (&$arr,$low,$high){ $i=$low; $j=$high+ 1; $choosen=$arr[$low]; while(1){ while($arr[++$i] <$choosen){//from the left to find the big, the big swap to the right if($i>=$high) Break; } while($arr[--$j] >$choosen){//from the right, find the small, swap it to the left. if($j<=$low) Break; } if($i>=$j) Break;//look from left to right, or from right to left, note that you can't cross ... Otherwise exit the Loop $temp=$arr[$i]; $arr[$i] =$arr[$j]; $arr[$j] =$temp; //Echo ' <br/> ', $low, ', $high, ' <br/> '; } $temp=$arr[$low]; $arr[$low] =$arr[$j]; $arr[$j] =$temp; return $j;//return to split point}//Recursive Quick SortfunctionQsort (&$arr,$low,$high){ if($low>=$high)return; $i= Slicearr ($arr,$low,$high);//the split point for this stepQsort$arr,$low,$i-1);//Recursive invocationQsort$arr,$i+1,$high);}$arr=Array(12, 17, 13, 16, 19, 11, 4, 5, 9, 77, 18);Shuffle($arr);Echo' <pre> ';Print_r($arr); Qsort ($arr, 0,Count($arr)-1);//SortEcho' <pre> ';Print_r($arr);
Understanding how fast sorting can exchange values is especially critical, and the algorithm feels very witty. Deepen your understanding of the wisdom of algorithms
Quick-Sort PHP implementations