Created
December 8, 2012 02:45
-
-
Save piglovesyou/4238321 to your computer and use it in GitHub Desktop.
quicksort 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
/** | |
* @param {Array} array . | |
* @return {Array} A sorted array. | |
*/ | |
function quicksort(array) { | |
if (array.length === 0) return array; | |
var pivot = array.splice(0, 1)[0], | |
left = [], | |
right = [], | |
target; | |
while (array.length > 0) { | |
target = array.splice(0, 1)[0]; | |
if (target <= pivot) { | |
left.push(target); | |
} else { | |
right.push(target); | |
} | |
} | |
return quicksort(left).concat(pivot, quicksort(right)); | |
} | |
/** | |
* @param {string} string . | |
* @return {string} A sorted string. | |
*/ | |
function quicksortForString(string) { | |
if (string.length === 0) return string; | |
var pivot = string[0], | |
left = '', | |
right = '', | |
target; | |
string = string.substr(1); | |
while (string.length > 0) { | |
target = string[0]; | |
string = string.substr(1); | |
if (target <= pivot) { | |
left += target; | |
} else { | |
right += target; | |
} | |
} | |
return quicksortForString(left) + pivot + quicksortForString(right); | |
} | |
var assert = require('assert'); | |
assert.deepEqual(quicksort( | |
[2, 5, 7, 4, 7, 8, 3, 1, 3, 8, 9, 6, 7, 8, 6, 7, 2, 999, 1, 2, 3, 5]), | |
[1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 999]); | |
assert.deepEqual(quicksort([]), []); | |
assert.strictEqual(quicksortForString( | |
'The quick brown fox jumps over the lazy dog'), | |
' Tabcdeeefghhijklmnoooopqrrstuuvwxyz', | |
'Fail at String.'); | |
assert.strictEqual(quicksort(''), ''); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment