- 遍历数据到object内(需要对数据的次数进行计算),并找出最大值
- 遍历最大值,一次把object的数据放进去
- https://jsbin.com/gufuhogode/edit?js,console
```javascript
const countSort = (a) => {
const object = {}, result = [];
let max;
a.forEach(n => {
if (!max && max !== 0) {
max = n;
} else if (n > max) {
max = n;
}
object[n] = !object[n] ? 1 : object[n] += 1;
});
for(let i = 0; i <= max; i += 1) {
const count = object[i];
if (count) {
for(let j = 1; j <= count; j += 1) {
} } } return result; }result.push(i)
- https://jsbin.com/gufuhogode/edit?js,console
```javascript
const countSort = (a) => {
const object = {}, result = [];
let max;
a.forEach(n => {
if (!max && max !== 0) {
max = n;
} else if (n > max) {
max = n;
}
object[n] = !object[n] ? 1 : object[n] += 1;
});
for(let i = 0; i <= max; i += 1) {
const count = object[i];
if (count) {
for(let j = 1; j <= count; j += 1) {
console.log(‘——————‘, countSort([2, 1, 3, 1, 4]))
console.log(‘————‘, countSort([1,2,9,4,10,20,12])) // // // // [1, 2, 4, 9, 10, 12, 20] console.log(‘————‘, countSort([11,2,39,24,1,2,9])) // // // // [1, 2, 2, 9, 11, 24, 39] console.log(‘————‘, countSort([]))
// // // // [] console.log(‘————‘, countSort([1,1,1,1,1])) ```
