UNPKG

algorithmpool

Version:
26 lines (25 loc) 627 B
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; }