Sort n numbers in range from 0 to n ^ 2 | A function to do counting sort of arr [ ] according to the digit represented by exp . ; Output array ; Store count of occurrences in count [ ] ; Change count [ i ] so that count [ i ] now contains actual position of this digit in output [ ] ; Build the output array ; Copy the output array to arr [ ] , so that arr [ ] now contains sorted numbers according to current digit ; The main function to that sorts arr [ ] of size n using Radix Sort ; Do counting sort for first digit in base n . Note that instead of passing digit number , exp ( n ^ 0 = 1 ) is passed . ; Do counting sort for second digit in base n . Note that instead of passing digit number , exp ( n ^ 1 = n ) is passed . ; A utility function to print an array ; Since array size is 7 , elements should be from 0 to 48
function countSort ( arr , n , exp ) { let output = new Array ( n ) ; let count = new Array ( n ) ; count . fill ( 0 ) ; output . fill ( 0 ) ; let i ; for ( i = 0 ; i < n ; i ++ ) count [ i ] = 0 ; for ( i = 0 ; i < n ; i ++ ) count [ parseInt ( arr [ i ] / exp , 10 ) % n ] ++ ; for ( i = 1 ; i < n ; i ++ ) count [ i ] += count [ i - 1 ] ; for ( i = n - 1 ; i >= 0 ; i -- ) { output [ count [ parseInt ( arr [ i ] / exp , 10 ) % n ] - 1 ] = arr [ i ] ; count [ parseInt ( arr [ i ] / exp , 10 ) % n ] -- ; } for ( i = 0 ; i < n ; i ++ ) arr [ i ] = output [ i ] ; } function sort ( arr , n ) { countSort ( arr , n , 1 ) ; countSort ( arr , n , n ) ; } function printArr ( arr , n ) { for ( let i = 0 ; i < n ; i ++ ) document . write ( arr [ i ] + " " ) ; } let arr = [ 40 , 12 , 45 , 32 , 33 , 1 , 22 ] ; let n = arr . length ; document . write ( " " + " " ) ; printArr ( arr , n ) ; sort ( arr , n ) ; document . write ( " " + " " ) ; printArr ( arr , n ) ;