fix: 修复输入负数报错问题
This commit is contained in:
parent
a4390d0e0c
commit
5c16f3f3a1
@ -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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
Loading…
x
Reference in New Issue
Block a user