How to implement a fast sorting algorithm

Source: Internet
Author: User

Quick sort:

Code:

<?php/** Fast Sorting algorithm * 1. Find an element in the array as key, and generally take the first element of the array as key * 2. i=0, j= array Length-1 * 3. j--when Arr[j]<key, Arr[i] with arr[j] Swap position * 4. i++ when Arr[i]>key, Arr[i] with arr[j] Swap position * 5. 
Repeat 3,4 until i==j, complete. * 6. 
The left and right sets of elements separated by a key are then executed separately by 1,2,3,4,5 (recursion).  
      
* * $arr = array (); Create an array//This column more highlights: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/sjjg/for ($i =0; $i <20; $i + +) {array  
_push ($arr, Mt_rand (1,200)); Echo ' source arr: '. Implode (', ', $arr). '  
      
<br> ';  
      
Quicksort ($arr, 0, Count ($arr)-1);  
      
Echo ' sorted arr: '. Implode (', ', $arr);  
    Quick Sort function quicksort (& $arr, $low, $high) {if ($low >= $high) {return;  
    } $i = $low;  
    $j = $high; $flag = 1;  
      
    0:I action 1:j Action $key = $arr [$low];  
                    while ($i < $j) {switch ($flag) {case 0://I if ($arr [$i]> $key) {  
                    $tmp = $arr [$i]; $arr [$i= $arr [$j];  
                    $arr [$j] = $tmp;  
                $flag = 1;  
                }else{$i + +;  
      
            } break;  
                    Case 1://J if ($arr [$j]< $key) {$tmp = $arr [$i];  
                    $arr [$i] = $arr [$j];  
                    $arr [$j] = $tmp;  
                $flag = 0;  
                }else{$j--;  
        } break;  
      
    }//Left arr quicksort ($arr, $low, $i-1);  
      
Right arr quicksort ($arr, $i +1, $high); }?>

Author: csdn blog proud Snow star Maple

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.