first we need to understand the principle of fast sorting: find any element in the current array (the first element is typically selected), 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 it on the left side of the array, otherwise put it to the right of the array, and 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<?PHP//Quick Sort//array to sort $arr=Array(6,3,8,6,4,2,9,5,1); //functions for quick ordering functionQuick_sort ($arr) { //determines whether a 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 two empty array is defined $left=$right=Array(); //use a For loop to iterate over the first element as a comparison object for($i= 1;$i<$length;$i++) { //determine the size of the current element if($arr[$i]<$arr[0]){ $left[]=$arr[$i]; }Else{ $right[]=$arr[$i]; } } //Recursive invocation $left=quick_sort ($left); $right=quick_sort ($right); //Combine all the results return Array_merge($left,Array($arr[0]),$right); } //called Echo"<pre>"; Print_r(Quick_sort ($arr));
PHP Enables quick sorting