升序排列数组

  1. function countingSort(arr) {
  2. const large = Math.max(...arr);
  3. const small = Math.min(...arr);
  4. const size = large - small + 1;
  5. const count = new Array(size).fill(0);
  6. let idx = 0;
  7. for (let i = 0; i < arr.length; i++) {
  8. count[arr[i] - small]++;
  9. }
  10. for (let j = 0; j < size; j++) {
  11. while (count[j]) {
  12. arr[idx++] = j + small;
  13. count[j]--;
  14. }
  15. }
  16. return arr;
  17. }

算法测试

  1. console.log(countingSort([6, 2, 1, 8, 7, 5]));
  2. // [ 1, 2, 5, 6, 7, 8 ]
  3. console.log(countingSort([4, 7, 2, 5, 3, -1, 9, 0]));
  4. // [ -1, 0, 2, 3, 4, 5, 7, 9 ]
  5. console.log(countingSort([-12, -3, 3, 4, 3, 8]));
  6. // [ -12, -3, 3, 3, 4, 8 ]