Skip to content

Instantly share code, notes, and snippets.

@marcofiset
Last active December 15, 2015 04:59
Show Gist options
  • Save marcofiset/5205878 to your computer and use it in GitHub Desktop.
Save marcofiset/5205878 to your computer and use it in GitHub Desktop.
Recursive QuickSort in Javascript
Array.prototype.filter = function(callback) {
var result = [];
var length = this.length;
for (var i = 0; i < length; i++) {
if (callback(this[i])) {
result.push(this[i]);
}
}
return result;
};
Array.prototype.sort = function() {
if (this.length < 2) return this;
var pivot = this[Math.floor(this.length / 2)];
var less = this.filter(function(item) { return item < pivot; });
var equal = this.filter(function(item) { return item == pivot; });
var greater = this.filter(function(item) { return item > pivot; });
return less.sort().concat(equal, greater.sort());
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment