- 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)