Skip to content

Instantly share code, notes, and snippets.

@kidGodzilla
Created December 30, 2014 09:24
Show Gist options
  • Save kidGodzilla/4dd9d782400bbd895afc to your computer and use it in GitHub Desktop.
Save kidGodzilla/4dd9d782400bbd895afc to your computer and use it in GitHub Desktop.
Quicksort in JavaScript
function randomArray() {
for (var a=[], i=0; ++i < 19;) a.push(~~(Math.random() * 100));
return a;
}
function quicksort(a) {
var l = [], r = [], m;
if(!a.length) return [];
m = a.pop();
while (a.length) {
a[0] < m ? l.push(a.shift()) : r.push(a.shift());
}
return quicksort(l).concat(m, quicksort(r));
}
// Code golfed, 144 characters
s = function(a){l=[];r=[];if(!a.length)return[];for(m=a.pop();a.length;)a[0]<m?l.push(a.shift()):r.push(a.shift());return s(l).concat(m,s(r))}
console.log(ar = randomArray());
console.log(quicksort(ar));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment