PHP Enables quick sorting

Source: Internet
Author: User
Tags array length

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.