Last active
October 8, 2021 16:24
-
-
Save zbicin/4dc940a0726e5f445590d7e0d46fb0ab to your computer and use it in GitHub Desktop.
Counting Sort implementation in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function countingSort(inputArray) { | |
| const max = Math.max(...inputArray); | |
| const counters = new Array(max+1).fill(0); // or Int32Array without fill | |
| // count | |
| inputArray.forEach(inputValue => { | |
| counters[inputValue]++; | |
| }); | |
| // accumulate | |
| for(let i = 1; i<counters.length; i++) { | |
| counters[i] = counters[i] + counters[i-1]; | |
| } | |
| // shift | |
| for(let i = counters.length-1; i>=0; i--) { | |
| i === 0? counters[i] = 0 : counters[i] = counters[i-1]; | |
| } | |
| const result = new Array(inputArray.length); | |
| for(let i = 0; i<inputArray.length; i++) { | |
| const inputValue = inputArray[i]; | |
| const startingIndex = counters[inputValue]; | |
| result[startingIndex] = inputValue; | |
| counters[inputValue]++; | |
| } | |
| return result; | |
| } | |
| /* | |
| function testCase() { | |
| const input = [4,2,2,8,3,3,1]; | |
| const expected = [1,2,2,3,3,4,8]; | |
| const actual = countingSort(input); | |
| if(actual.toString() !== expected.toString()) { | |
| throw new Error(`Expected ${expected.toString()} got ${actual.toString()}`) | |
| } | |
| } | |
| testCase(); | |
| */ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function countingSort(arr) { | |
| const max = Math.max(...arr); | |
| const counters = new Array(max+1); | |
| counters.fill(0); | |
| arr.forEach(inputItem => { | |
| counters[inputItem]++; | |
| }); | |
| for(let i = 1; i<counters.length; i++) { | |
| counters[i] += counters[i-1]; | |
| } | |
| const output = new Array(counters.length); | |
| arr.forEach(inputItem => { | |
| const count = counters[inputItem]; | |
| output[count-1] = inputItem; | |
| counters[inputItem]--; | |
| }) | |
| const result = new Array(arr.length); | |
| arr.forEach((inputItem, i) => { | |
| result[i] = typeof output[i] !== `undefined` ? output[i] : inputItem; | |
| }); | |
| return result; | |
| } | |
| /* | |
| function testCase() { | |
| const input = [4,2,2,8,3,3,1]; | |
| const expected = [1,2,2,3,3,4,8]; | |
| const actual = countingSort(input); | |
| if(actual.toString() !== expected.toString()) { | |
| throw new Error(`Expected ${expected.toString()} got ${actual.toString()}`) | |
| } | |
| } | |
| testCase(); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment