PHP Recursive Method for fast sorting, php recursive sorting example
This example describes how to implement quick sorting by recursive PHP. We will share this with you for your reference. The details are as follows:
First, we need to understandPrinciples of fast sorting: Find any element in the current array (usually the first element), as the standard, create two empty arrays, traverse the entire array element, if the element to be traversed is smaller than the current element, put it in the array on the left; otherwise, put it in the array on the right, and then perform the same operation on the new array.
It is not difficult to find that the recursion principle is met here, so we can implement it using recursion.
To use recursion, you need to find the recursion point and exit:
Recursive point:If the element of the array is greater than 1, it needs to be decomposed. Therefore, our recursive point is that the number of newly constructed array elements is greater than 1.
Recursive Exit:When do we no longer need to sort the new array? That is, when the number of array elements changes to 1, this is our exit.
After understanding the principle, let's take a look at the code implementation ~
<? Php // quick sorting // The array to be sorted $ arr = array (6, 3, 8, 6, 4, 2, 9, 5, 1); // The function implements quick sorting function quick_sort ($ arr) {// determine whether the parameter is an array if (! Is_array ($ arr) return false; // recursive Exit: the array length is 1, and the returned array $ length = count ($ arr); if ($ length <= 1) return $ arr; // if multiple array elements exist, two empty arrays $ left = $ right = array () are defined. // use the for loop for traversal, use the first element as the 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 call $ left = quick_sort ($ left); $ right = quick_sort ($ right ); // merge all results return array_merge ($ left, array ($ arr [0]), $ right);} // call echo "<pre> "; print_r (quick_sort ($ arr ));
Running result:
Array( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 6 [7] => 8 [8] => 9)
PS: here we recommend a demo tool for sorting for your reference:
Online animation demo insert/select/bubble/merge/hill/Quick Sort Algorithm process tool:
Http://tools.jb51.net/aideddesign/paixu_ys