Quick-Sort PHP implementations

Source: Internet
Author: User

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

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.