Javascript中的基數排序?
基數排序演算法根據數字的有效位或值(基數)將整數分配到幾個儲存桶中。基數基於陣列中值的數字系統。讓我們看看如何實現它 −
示例
function radixSort(arr) {
// Find the max number and multiply it by 10 to get a number
// with no. of digits of max + 1
const maxNum = Math.max(...arr) * 10;
let divisor = 10;
while (divisor < maxNum) {
// Create bucket arrays for each of 0-9
let buckets = [...Array(10)].map(() => []);
// For each number, get the current significant digit and put it in the respective bucket
for (let num of arr) {
buckets[Math.floor((num % divisor) / (divisor / 10))].push(num);
}
// Reconstruct the array by concatinating all sub arrays
arr = [].concat.apply([], buckets);
// Move to the next significant digit
divisor *= 10;
}
return arr;
}
console.log(radixSort([5,3,88,235,65,23,4632,234]))輸出
[ 3, 5, 23, 65, 88, 234, 235, 4632 ]
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
安卓
Python
C語言
C++
C#
MongoDB
MySQL
Javascript
PHP