Skip to content

Commit 91dcad6

Browse files
committed
add radixSort file
1 parent a8e1fca commit 91dcad6

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

Diff for: Sort/radixSort.js

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/* RADIX SORT */
2+
//TIME coplexity: O(nk)
3+
//SPACE coplexity:O(n+k)
4+
5+
//n = length of array
6+
//k = number of max digit
7+
8+
//a sort algorithm for numbers:)
9+
10+
function getDigit(number, index) {
11+
let str = number.toString();
12+
str = str.split('').reverse().join('');
13+
return index < str.length ? parseInt(str[index]) : 0;
14+
}
15+
16+
17+
function getDigit2(number, index) {
18+
return Math.floor(Math.abs(number) / Math.pow(10, index)) % 10;
19+
}
20+
21+
function digitCount1(number) {
22+
return number.toString().length;
23+
}
24+
25+
26+
function digitCount2(number) {
27+
if (number === 0)
28+
return 1;
29+
return Math.floor(Math.log10(Math.abs(number))) + 1;
30+
}
31+
32+
33+
function mostDigits(arr) {
34+
let num_largerst = 0;
35+
let digitcount;
36+
for (const num of arr) {
37+
digitcount = digitCount1(num)
38+
if (digitcount > num_largerst) {
39+
num_largerst = digitcount;
40+
}
41+
}
42+
return num_largerst;
43+
}
44+
45+
function mostDigits2(nums) {
46+
let maxDigits = 0;
47+
for (let i = 0; i < nums.length; i++) {
48+
maxDigits = Math.max(maxDigits, digitCount1(nums[i]));
49+
}
50+
return maxDigits;
51+
}
52+
53+
function radixSort(arr) {
54+
let mostdigits = mostDigits(arr);
55+
56+
for (let i = 0; i < mostdigits; i++) {
57+
let digitBuckets = Array.from({ length: 10 }, () => []); //create 10 subarrays
58+
for (let j = 0; j < arr.length; j++) {
59+
let digit = getDigit(arr[j], i);
60+
digitBuckets[digit].push(arr[j]);
61+
}
62+
arr = [].concat(...digitBuckets);
63+
// console.log(digitBuckets);
64+
}
65+
return arr;
66+
}
67+
68+
console.log(getDigit(12345, 0));
69+
console.log(getDigit(12345, 1));
70+
console.log(getDigit(12345, 2));
71+
console.log(getDigit(12345, 3));
72+
console.log(getDigit(12345, 4));
73+
console.log(getDigit(12345, 5));
74+
75+
76+
console.log(digitCount1(12345));
77+
console.log(digitCount2(12345));
78+
79+
80+
console.log(mostDigits([1234567, 3, 45, 132]));
81+
console.log(mostDigits2([1234567, 3, 45, 132]));
82+
83+
84+
console.log(radixSort([23, 345, 5437, 166, 3]));

0 commit comments

Comments
 (0)