Skip to content

Instantly share code, notes, and snippets.

@petercr
Created February 25, 2022 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petercr/fee5a17d7ff8733d62cad07239573a44 to your computer and use it in GitHub Desktop.
Save petercr/fee5a17d7ff8733d62cad07239573a44 to your computer and use it in GitHub Desktop.
Solution to the Hackerrank Algorithm for Couting Sort 1
function countingSort(arr) {
// Create new Array to hold sorted values
const results = new Array(10).fill(0);
// Loop through array and add values to results array
for (let i = 0; i < arr.length; i++) {
const currentNum = parseInt(arr[i], 10);
if (typeof results[i] === undefined) {
results[i] = 0;
}
if (typeof results[currentNum] === undefined) {
results[currentNum] = 1;
} else {
results[currentNum] += 1;
}
}
return results;
}
const test1 = countingSort([1, 1, 2, 2, 3]);
console.log(test1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment