<? Php # Randomly select a number smaller than I, and implement it in a random fast rank.
# Swap Element Function swap (& $ arr, $ I, $ j ){ $ Temp = $ arr [$ I]; $ Arr [$ I] = $ arr [$ j]; $ Arr [$ j] = $ temp; } # Random division Function randomized_partition (& $ arr, $ begin, $ end ){ $ Rand_tables = rand ($ begin, $ end ); Swap ($ arr, $ begin, $ rand_inx ); Return partition ($ arr, $ begin, $ end ); } # Division Function partition (& $ arr, $ begin, $ end ){ # Use the first element as the central element $ Begin = $ begin; $ Low = $ begin; $ High = $ end; While ($ low <$ high ){ While ($ low <$ high & $ arr [$ low] <= $ arr [$ slow]) { $ Low ++; } While ($ low <$ high & $ arr [$ high] >=$ arr [$ hour]) { $ High --; } Swap ($ arr, $ low, $ high ); } # Central element exchange If ($ arr [$ Scheme] <$ arr [$ low]) { $ Low --; } Swap ($ arr, $ scheme, $ low ); Return $ low; } # Fast sorting, not used here Function quick_sort (& $ arr, $ begin, $ end ){ $ Q = randomized_partition ($ arr, $ begin, $ end ); If ($ q> $ begin ){ Quick_sort ($ arr, $ begin, $ q-1 ); } If ($ q <$ end ){ Quick_sort ($ arr, $ q + 1, $ end ); } } # Select the number smaller than I Function randomized_select (& $ arr, $ begin, $ end, $ I ){ If ($ begin ==$ end ){ Return $ arr [$ begin]; } $ Q = randomized_partition ($ arr, $ begin, $ end ); $ K = $ q-$ begin + 1; # k indicates the number of elements less than or equal to q. If ($ k = $ I) {# if k = I, q is the element coordinate smaller than I. Return $ arr [$ q]; } Else if ($ I <$ k) {# if I <k, the element smaller than I is on the left of q Return randomized_select ($ arr, $ begin, $ q-1, $ I ); } Else {# The element smaller than I is located on the right of q. In this case, find the element smaller than I-k on the right. Return randomized_select ($ arr, $ q + 1, $ end, $ I-$ k ); } } $ Arr = array (1, 5, 3, 7, 0, 0, 8, 4, 2, 9, 11 ); $ T = randomized_select ($ arr, 0, count ($ arr)-1, 8 ); Print_r ("The 8th minimum element: {$ t }"); Echo "<br> "; Quick_sort ($ arr, 0, count ($ arr)-1 ); Print_r ($ arr ); ?> |