fix: 修复输入负数报错问题

This commit is contained in:
LouisFonda 2024-03-05 19:09:36 +08:00
parent a4390d0e0c
commit 5c16f3f3a1

View File

@ -8,6 +8,21 @@ function radixSort(arr) {
let max = Math.abs(Math.max(...arr)); // 拿取数组中最大的数,用于计算长度
let buckets = Array.from({ length: 10 }, () => []);
let curDit = 1; // 当前比较的是哪个数位 1表示个位
/* 使
倒序添加到原数组的前面
*/
let negativeArr = [];
const tempArr = [];
for (let i = 0; i < arr.length; i++) {
const temp = arr[i];
if (temp < 0) {
negativeArr.push(temp);
} else {
tempArr.push(temp);
}
}
arr = tempArr;
if (negativeArr.length) negativeArr = radixSort(negativeArr.map((_) => -_)).map((_) => -_);
while (Math.floor(max)) {
for (let i = 0; i < arr.length; i++) {
buckets[getNumByGidit(arr[i], curDit)].push(arr[i]); // 根据数位的大小放入对应的数位桶中
@ -22,7 +37,7 @@ function radixSort(arr) {
max /= 10; // 处理下一数位
curDit++;
}
return arr;
return negativeArr.length ? negativeArr.reverse().concat(arr) : arr;
}
/**