This paper mainly introduces the recursive implementation of PHP fast ordering method, a simple description of the principle of rapid sequencing and the use of examples to analyze PHP using recursive algorithm to achieve rapid sequencing of the relevant operation skills, the need for friends can refer to, hope to help everyone.
First of all, we need to understand the principle of fast sorting: Find any element in the current array (generally select the first element), as a standard, create a new two empty array, traverse the entire array element, if the traversed element is smaller than the current element, then put to the left of the array, otherwise put to the right of the array, Then do the same for the new array.
It is not difficult to find that this is consistent with the principle of recursion, so we can use the recursive return to achieve.
With recursion, you need to find a recursive point and a recursive exit:
Recursion point: If the element of the array is greater than 1, it needs to be decomposed again, so our recursive point is that the number of newly constructed array elements is greater than 1
Recursive exit: When do we not have to sort the new arrays again? is when the number of array elements becomes 1, so this is our exit.
Understand the principle, look at the code implementation ~
<?php//Quick Sort//Sort array $arr=array (6,3,8,6,4,2,9,5,1);//function Implementation Quick Sort functions Quick_sort ($arr) { //Determine if the parameter is an array if (!is_array ($arr)) return false; Recursive exit: Array length is 1, return array directly $length =count ($arr); if ($length <=1) return $arr; array element has multiple, then define two empty array $left = $right =array (); Using a For loop, use the first element as the object of comparison for ($i =1; $i < $length; $i + +) { //To determine the size of the current element if ($arr [$i]< $arr [0 ] { $left []= $arr [$i]; } else{ $right []= $arr [$i]; } } Recursive call $left =quick_sort ($left); $right =quick_sort ($right); Merge all results into return Array_merge ($left, Array ($arr [0]), $right);} Call echo "<pre>";p Rint_r (Quick_sort ($arr));
Operation Result:
Array ( [0] = 1 [1] = 2 [2] = 3 [3] = 4 [4] = 5 [5] = 6 [6] => ; 6 [7] = 8 [8] = 9)