Created
August 18, 2014 04:26
-
-
Save natemcmaster/9e9ba5b9d27938618e0f to your computer and use it in GitHub Desktop.
Simple implementation of quicksort in JS
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 quickSort(arr) { | |
sort(arr, 0, arr.length - 1); | |
return arr; | |
} | |
function swap(arr, m, n) { | |
var tmp = arr[m]; | |
arr[m] = arr[n]; | |
arr[n] = tmp; | |
} | |
function sort(arr, left, right) { | |
if (left >= right) { | |
return; | |
} | |
var p = partition(arr, left, right); | |
if (left < p - 1) { | |
sort(arr, left, p - 1); | |
} | |
if (right > p); { | |
sort(arr, p, right); | |
} | |
} | |
function partition(arr, left, right) { | |
var mid = Math.floor((left + right) / 2); | |
var pivot = arr[mid]; | |
while (left <= right) { | |
while (arr[left] < pivot) { | |
left++; | |
} | |
while (arr[right] > pivot) { | |
right--; | |
} | |
if (left <= right) { | |
swap(arr, left, right); | |
left++; | |
right--; | |
} | |
} | |
return left; | |
} | |
module.exports = quickSort; |
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 quickSort = require('./quicksort'); | |
var arr = [1, 3, -234, 46, 14]; | |
var sorted = quickSort(arr); | |
assertSorted(arr); | |
console.log("Expected", [].concat(arr).sort(function(a, b) { | |
return a > b; | |
})); | |
console.log("Actual", sorted); | |
for (var i = 2000; i <= 10000000; i *= 2) { | |
var rand = []; | |
for (var j = 0; j < i; j++) { | |
rand[j] = Math.floor(Math.random() * 10000000); | |
} | |
var label = i + ' elements'; | |
console.time(label); | |
quickSort(rand); | |
console.timeEnd(label); | |
assertSorted(rand); | |
} | |
function assertSorted(arr) { | |
return arr.reduce(function(a, b) { | |
if (a > b) { | |
throw new Error("Array not sorted") | |
} | |
return b; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment