Skip to content

Instantly share code, notes, and snippets.

@kylejeske
Created August 30, 2019 15:12
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 kylejeske/4cf0782b4c9274b14ac25d0cef0d5d83 to your computer and use it in GitHub Desktop.
Save kylejeske/4cf0782b4c9274b14ac25d0cef0d5d83 to your computer and use it in GitHub Desktop.
Counting Sort Algorithm - Implemented in JavaScript
/**
* Using counting sort algorithm
*
* Take an Array from:
* [1, 4, 1, 2, 7, 5, 2]
* to
* [1, 1, 2, 2, 4, 5, 7]
*/
((Arr) => {
// Arr: Unsorted - Zero-based Indicies Array
// lookupTable: Zero-Based Indicies (0-9)
let LookupTable = Array.from({ length: 9 }, () => 0);
// ArrSorted: Sorted One-Based Indicies Array
let ArrSorted = [null];
// Functions
const buildLookupTable = table => (value) => table[value]
? table[value]++
: (table[value] = 1);
const getSumOfIndicies = (curr, pA, arr) => {
// we work of a one-based index for this loop
if (pA == 0) {
return;
}
let pB = (pA + 1);
let next = (arr[pB] ? parseInt(arr[pB], 10) : 0);
arr[pB] = curr + next;
}
const buildSortedArray = lookupTable => sortedArray => (value) => {
sortedArray[lookupTable[value]] = value;
lookupTable[value]--;
}
// Procedural Steps
// Step 1:
// Build the lookup Reference Table
Arr
.map(key => buildLookupTable(LookupTable)(key));
// Step 2:
// Get the Sum of the indicies
LookupTable
.forEach(getSumOfIndicies);
// Step 3:
// Using the lookup table, produce a sorted array
Arr
.map(value => buildSortedArray(LookupTable)(ArrSorted)(value))
// CleanUp:
// removes the unnecessary 'null' at zero-index
ArrSorted.shift();
console.log(`Starting with Unsorted Array: \n${Arr}`);
console.log(`Build our lookup table: \n${LookupTable}`);
console.log(`Produce a Sorted Array: \n${ArrSorted}`);
return ArrSorted;
})([1, 4, 1, 2, 7, 5, 2]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment