Skip to content

Instantly share code, notes, and snippets.

@josephok
Created May 13, 2015 10:34
Show Gist options
  • Save josephok/7e78ed674f347202b5c6 to your computer and use it in GitHub Desktop.
Save josephok/7e78ed674f347202b5c6 to your computer and use it in GitHub Desktop.
quick sort in Javascript
var quickSort = function(arr) {
if (!Array.isArray(arr)) throw new Error("arguments should be an array");
  if (arr.length <= 1) { return arr; }
  var pivotIndex = Math.floor(arr.length / 2);
  var pivot = arr.splice(pivotIndex, 1)[0];
  var left = [];
  var right = [];
  for (var i = 0; i < arr.length; i++){
    if (arr[i] < pivot) {
      left.push(arr[i]);
    } else {
      right.push(arr[i]);
    }
  }
  return quickSort(left).concat([pivot], quickSort(right));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment