algorithmpool
Version:
A pool of algorithms and data-structures for geeks
26 lines (25 loc) • 627 B
JavaScript
import {
findMaxValue
} from '../search/maxMinSearch';
export const countingSort = (array) => {
if (array.length < 2) {
return array;
}
const maxValue = findMaxValue(array);
let sortedIndex = 0;
const counts = new Array(maxValue + 1);
array.forEach(element => {
if (!counts[element]) {
counts[element] = 0;
}
counts[element]++;
});
// console.log('Frequencies: ' + counts.join());
counts.forEach((element, i) => {
while (element > 0) {
array[sortedIndex++] = i;
element--;
}
});
return array;
}