Skip to content

Instantly share code, notes, and snippets.

@jwchang0206
Created May 16, 2014 21:30
Show Gist options
  • Save jwchang0206/baa00041977e1622a6cb to your computer and use it in GitHub Desktop.
Save jwchang0206/baa00041977e1622a6cb to your computer and use it in GitHub Desktop.
'use strict';
var arr = [6, 5, 3, 1, 8, 7, 2, 4];
function partition(arr, lp, rp) {
var middle = Math.floor((lp + rp) / 2),
pivot = arr[middle],
temp;
while (lp <= rp) {
while (arr[lp] < pivot) lp++;
while (arr[rp] > pivot) rp--;
if (lp <= rp) {
temp = arr[lp];
arr[lp] = arr[rp];
arr[rp] = temp;
lp++;
rp--;
}
}
return lp;
}
function quickSort(arr, lp, rp) {
var index;
lp = lp || 0;
rp = rp || arr.length - 1;
if (arr.length > 1) {
index = partition(arr, lp, rp);
if (lp < index - 1)
quickSort(arr, lp, index - 1);
if (index < rp)
quickSort(arr, index, rp);
}
return arr;
}
console.log(quickSort(arr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment