|
| 1 | +# A function to do counting sort of arr[] according to |
| 2 | +# the digit represented by exp. |
| 3 | + |
| 4 | +defcountingSort(arr,exp1): |
| 5 | + |
| 6 | +n=len(arr) |
| 7 | + |
| 8 | +# The output array elements that will have sorted arr |
| 9 | +output= [0]* (n) |
| 10 | + |
| 11 | +# initialize count array as 0 |
| 12 | +count= [0]* (10) |
| 13 | + |
| 14 | +# Store count of occurrences in count[] |
| 15 | +foriinrange(0,n): |
| 16 | +index= (arr[i]/exp1) |
| 17 | +count[int(index%10)]+=1 |
| 18 | + |
| 19 | +# Change count[i] so that count[i] now contains actual |
| 20 | +# position of this digit in output array |
| 21 | +foriinrange(1,10): |
| 22 | +count[i]+=count[i-1] |
| 23 | + |
| 24 | +# Build the output array |
| 25 | +i=n-1 |
| 26 | +whilei>=0: |
| 27 | +index= (arr[i]/exp1) |
| 28 | +output[count[int(index%10)]-1]=arr[i] |
| 29 | +count[int(index%10)]-=1 |
| 30 | +i-=1 |
| 31 | + |
| 32 | +# Copying the output array to arr[], |
| 33 | +# so that arr now contains sorted numbers |
| 34 | +i=0 |
| 35 | +foriinrange(0,len(arr)): |
| 36 | +arr[i]=output[i] |
| 37 | + |
| 38 | +defradixSort(arr): |
| 39 | + |
| 40 | +# Find the maximum number to know number of digits |
| 41 | +max1=max(arr) |
| 42 | + |
| 43 | +# Do counting sort for every digit. Note that instead |
| 44 | +# of passing digit number, exp is passed. exp is 10^i |
| 45 | +# where i is current digit number |
| 46 | +exp=1 |
| 47 | +whilemax1/exp>0: |
| 48 | +countingSort(arr,exp) |
| 49 | +exp*=10 |
| 50 | + |
| 51 | + |
| 52 | +arr= [170,45,75,90,802,24,2,66] |
| 53 | + |
| 54 | +radixSort(arr) |
| 55 | + |
| 56 | +foriinrange(len(arr)): |
| 57 | +print(arr[i]) |