Created
February 28, 2012 04:52
-
-
Save bmitchelmore/1929681 to your computer and use it in GitHub Desktop.
In Place Radix Sort in Javascript
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
var nums = [35, 25, 53, 3, 102, 203, 230, 1005]; | |
// Figure out the number of binary digits we're dealing with | |
var k = Math.max.apply(null, nums.map(function(i) { | |
return Math.ceil(Math.log(i)/Math.log(2)); | |
})); | |
for (var d = 0; d < k; ++d) { | |
for (var i = 0, p = 0, b = 1 << d, n = nums.length; i < n; ++i) { | |
var o = nums[i]; | |
if ((o & b) == 0) { | |
// this number is a 0 for this digit | |
// move it to the front of the list | |
nums.splice(p++, 0, nums.splice(i, 1)[0]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a version I came up with which seems pretty stable while sorting in place on the original input data. So far I've only tested it up to about 500,000 integers. This version will sort positive integer values ranging from 0 - 99, but is easily scale-able if you recognize the repetitive patterns which only differ in the enqueue process in which data[i]'s divisor grows in multiples of ten. So for example if you needed to scale this to support integers ranging from 0 - 999, you would just repeat the code block again but divide data[i] in the enqueue process by 100.