Last active
November 21, 2017 00:55
-
-
Save Daniel-Hug/2aafc5a50bd230d5e4debec8e03190a7 to your computer and use it in GitHub Desktop.
JS functions: linear time counting sort for integers
This file contains 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, min, max) { | |
var i, z = 0, count = []; | |
for (i = min; i <= max; i++) { | |
count[i] = 0; | |
} | |
for (i=0; i < arr.length; i++) { | |
count[arr[i]]++; | |
} | |
for (i = min; i <= max; i++) { | |
while (count[i]-- > 0) { | |
arr[z++] = i; | |
} | |
} | |
return arr; | |
} | |
function countingSortUnknownRange(arr) { | |
var counts = []; | |
for (var i=0; i < arr.length; i++) { | |
if (counts[arr[i]] === undefined) { | |
counts[arr[i]] = 1; | |
} else { | |
counts[arr[i]]++; | |
} | |
} | |
var z = 0; | |
counts.forEach(function(count, val) { | |
while (count-- > 0) { | |
arr[z++] = val; | |
} | |
}); | |
return arr; | |
} | |
// 1. Map each item in the input array to an integer | |
// representing its proper order in the resulting array. | |
// 2. Use each integer as an index in a sparse array to point | |
// to an array of the values which returned that integer. | |
// 3. Replace the items in the passed array, but with the new order | |
// they have in the sparse array (or in reverse if desc is truthy). | |
function mapCountingSort(arr, mapFn, desc) { | |
var z = desc ? arr.length : 0; | |
var valsByInt = []; | |
for (var i=0; i < arr.length; i++) { | |
var int = mapFn(arr[i]); // 1 | |
if (valsByInt[int] === undefined) { | |
valsByInt[int] = [arr[i]]; // 2 | |
} else { | |
valsByInt[int].push(arr[i]); | |
} | |
} | |
valsByInt.forEach(desc ? function(vals, val) { | |
for (var i = 0; i < vals.length; i++) { | |
arr[--z] = vals[i]; // 3 | |
} | |
} : function(vals, val) { | |
for (var i = 0; i < vals.length; i++) { | |
arr[z++] = vals[i]; // 3 | |
} | |
}); | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment