Last active
December 15, 2015 04:59
-
-
Save marcofiset/5205878 to your computer and use it in GitHub Desktop.
Recursive 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
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