升序排列数组

  1. function radixSort(arr) {
  2. const radixBase = 10;
  3. const buckets = [];
  4. for (let i = 0; i < radixBase; i++) {
  5. buckets[i] = [];
  6. }
  7. let maxValue = Math.max(...arr);
  8. let digits = 0;
  9. do {
  10. digits++;
  11. maxValue = Math.floor(maxValue / radixBase);
  12. } while (maxValue !== 0);
  13. let placement = 1;
  14. for (let i = 0; i < digits; i++) {
  15. for (let i = 0; i < arr.length; i++) {
  16. let temp = arr[i] / placement;
  17. buckets[Math.floor(temp % radixBase)].push(arr[i]);
  18. }
  19. let p = 0;
  20. for (let j = 0; j < radixBase; j++) {
  21. const buck = buckets[j];
  22. while (buck.length) {
  23. arr[p] = buck.shift();
  24. p++;
  25. }
  26. }
  27. placement *= 10;
  28. }
  29. return arr;
  30. }

算法测试

  1. console.log(radixSort([12, 2, 1, 28, 27, 56, 123]));
  2. // [ 1, 2, 12, 27, 28, 56, 123 ]
  3. console.log(radixSort([412, 7, 102, 55, 3333, 1, 99, 100]));
  4. // [ 1, 7, 55, 99, 100, 102, 412, 3333 ]
  5. console.log(radixSort([12, 2, 0, 4, 3, 8]));
  6. // [ 0, 2, 3, 4, 8, 12 ]