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 ]

更新日期: 2019 年 9 月 16 日

219 次瀏覽

開啟你的 事業

完成課程認證

開始學習
廣告
© . All rights reserved.