@@ -7,34 +7,35 @@ const getDigit = (num: number, place: number) => {
7
7
const digitCount = ( num : number ) => {
8
8
// log 0
9
9
if ( num === 0 ) return 1 ;
10
- return Math . floor ( Math . log10 ( num ) ) + 1 ;
10
+ return Math . floor ( Math . log10 ( Math . abs ( num ) ) ) + 1 ;
11
11
} ;
12
12
13
- // returns the number of digits in the largest number of the list nums
14
- const mostDigits = ( nums : number [ ] ) => {
13
+ // returns the number of digits in the largest number of the list arr
14
+ const maximumDigits = ( arr : number [ ] ) => {
15
15
let max = 0 ;
16
- for ( let i = 0 ; i < nums . length ; i ++ ) {
17
- max = Math . max ( max , nums [ i ] ) ;
16
+ for ( let n of arr ) {
17
+ max = Math . max ( max , digitCount ( n ) ) ;
18
18
}
19
+
19
20
return max ;
20
21
} ;
21
22
22
- const radixSort = ( nums : number [ ] ) => {
23
- let maxDigits = mostDigits ( nums ) ;
23
+ const radixSort = ( arr : number [ ] ) => {
24
+ let maxDigits = maximumDigits ( arr ) ;
24
25
// put each digit from each num in the right bucket
25
26
for ( let i = 0 ; i < maxDigits ; i ++ ) {
26
27
// an array of 10 empty arrays, a bucket to each possible number
27
28
let digitBuckets : number [ ] [ ] = Array . from ( { length : 10 } , ( ) => [ ] ) ;
28
- for ( let j = 0 ; j < nums . length ; j ++ ) {
29
- // take the digit of nums [j]
30
- let digit = getDigit ( nums [ j ] , i ) ;
31
- // add this nums [j] in the bucket of the right digit
32
- digitBuckets [ digit ] . push ( nums [ j ] ) ;
29
+ for ( let j = 0 ; j < arr . length ; j ++ ) {
30
+ // take the digit of arr [j]
31
+ let digit = getDigit ( arr [ j ] , i ) ;
32
+ // add this arr [j] in the bucket of the right digit
33
+ digitBuckets [ digit ] . push ( arr [ j ] ) ;
33
34
}
34
35
// to concate each element from each bucket, using spread
35
- nums = Array . prototype . concat ( ...digitBuckets ) ;
36
+ arr = Array . prototype . concat ( ...digitBuckets ) ;
36
37
}
37
- return nums ;
38
+ return arr ;
38
39
} ;
39
40
40
- export = radixSort ;
41
+ export default radixSort ;
0 commit comments