|
| 1 | +<?php |
| 2 | + |
| 3 | +function countSort(&$arr, $n, $exp) |
| 4 | +{ |
| 5 | + // output array |
| 6 | + $output = array_fill(0, $n, 0); |
| 7 | + $count = array_fill(0, 10, 0); |
| 8 | + |
| 9 | + // Store count of occurrences in count[] |
| 10 | + for ($i = 0; $i < $n; $i++) |
| 11 | + $count[ ($arr[$i] / $exp) % 10 ]++; |
| 12 | + |
| 13 | + // contains actual position of this digit in output[] |
| 14 | + for ($i = 1; $i < 10; $i++) |
| 15 | + $count[$i] += $count[$i - 1]; |
| 16 | + |
| 17 | + // Build the output array |
| 18 | + for ($i = $n - 1; $i >= 0; $i--) |
| 19 | + { |
| 20 | + $output[$count[ ($arr[$i] / $exp) % 10 ] - 1] = $arr[$i]; |
| 21 | + $count[ ($arr[$i] / $exp) % 10 ]--; |
| 22 | + } |
| 23 | + |
| 24 | + // Copy the output array to arr[] |
| 25 | + for ($i = 0; $i < $n; $i++) |
| 26 | + $arr[$i] = $output[$i]; |
| 27 | +} |
| 28 | + |
| 29 | +// The main function that sorts arr[] |
| 30 | +function radixsort(&$arr, $n) |
| 31 | +{ |
| 32 | + // Find the maximum number to know number of digits |
| 33 | + $m = max($arr); |
| 34 | + |
| 35 | + // Do counting sort for every digit |
| 36 | + for ($exp = 1; $m / $exp > 0; $exp *= 10) |
| 37 | + countSort($arr, $n, $exp); |
| 38 | +} |
| 39 | + |
| 40 | +// A utility function to print an array |
| 41 | +function PrintArray(&$arr,$n) |
| 42 | +{ |
| 43 | + echo "sorted Array : "; |
| 44 | + for ($i = 0; $i < $n; $i++) |
| 45 | + echo $arr[$i] . " "; |
| 46 | +} |
| 47 | + |
| 48 | +// Driver Code |
| 49 | +$n = readline ("Enter size of an array : "); |
| 50 | +readline ("Enter the elements : "); |
| 51 | +for ($i = 0; $i < $n; $i++) |
| 52 | +{ |
| 53 | + $arr[$i] = readline(); |
| 54 | +} |
| 55 | + |
| 56 | +radixsort($arr, $n); |
| 57 | +PrintArray($arr, $n); |
| 58 | + |
| 59 | +/* |
| 60 | +OUTPUT: |
| 61 | +Enter size of an array : 7 |
| 62 | +Enter the elements : |
| 63 | +12 |
| 64 | +45 |
| 65 | +9 |
| 66 | +85 |
| 67 | +700 |
| 68 | +2 |
| 69 | +4 |
| 70 | +Sorted Array : 2 4 9 12 45 85 700 |
| 71 | +*/ |
| 72 | + |
| 73 | +?> |
0 commit comments