PHP quick sorting

Source: Internet
Author: User
  • Average efficiency o (nlogn) of the fast sort, preferably O (nlogn). The worst case is that when the array is ordered, it degrades to O (N ^ 2)
1 <? PHP 2 # Quick sorting 3 # @ Param $ arr array to be sorted 4 # @ Param $ start Coordinate 5 # @ Param $ end Coordinate 6 function quicksort (Array & $ arr, $ start, $ end) {7 $ low = $ start; 8 $ high = $ end; 9 10 # Move low and high at the same time, low finds elements larger than $ arr [$ start], and high finds elements smaller than $ arr [$ start]. 11 # positions of swap size elements, know low = high12 while ($ low! = $ High) {13 while ($ arr [$ low] <= $ arr [$ start] & $ low! = $ High) {14 + + $ low; 15} 16 while ($ arr [$ high] >=$ arr [$ start] & $ low! = $ High) {17 -- $ high; 18} 19 $ temp = $ arr [$ low]; 20 $ arr [$ low] = $ arr [$ high]; 21 $ arr [$ high] = $ temp; 22} 23 24 # If the low and high points to less than $ arr [$ start], exchange $ arr [$ start] And this element 25 # Otherwise, exchange $ arr [$ start] and the previous element that low points to, and then enter recursion 26 if ($ low! = $ Start & $ arr [$ low]> $ arr [$ start]) $ low --; 27 $ temp = $ arr [$ low]; 28 $ arr [$ low] = $ arr [$ start]; 29 $ arr [$ start] = $ temp; 30 31 # the recursive stop condition is that the split part has only one element 32 if ($ low-1> $ start) quicksort ($ arr, $ start, $ low-1 ); 33 if ($ low + 1 <$ end) quicksort ($ arr, $ low + 1, $ end); 34} 35 36 $ arr = array (8, 8, 1, 1, 5, 3, 7, 9, 8, 4, 10); 37 quicksort ($ arr, 0, count ($ ARR)-1 ); 38 39 print_r ($ ARR); 40?>

Output

Array ([0] => 1 [1] => 1 [2] => 3 [3] => 4 [4] => 5 [5] => 7 [6] => 8 [7] => 8 [8] => 8 [9] => 9 [10] => 10)

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.