Skip to content

Instantly share code, notes, and snippets.

@iegik
Last active November 29, 2017 13:11
Show Gist options
  • Save iegik/73df8db69a2b7420ae4ae1ec240b888d to your computer and use it in GitHub Desktop.
Save iegik/73df8db69a2b7420ae4ae1ec240b888d to your computer and use it in GitHub Desktop.
Quick Sort
var a = [5,3,7,1,10,-1];
quicksort.call(a);
console.log(a); // -1, 1, 3, 5, 7, 10
function quicksort(lo, hi){
var k = Object.keys(this);
if(typeof lo === 'undefined')lo = k[0];
if(typeof hi === 'undefined')hi = k[k.length-1];
if (lo < hi){
var p = partition.call(this,lo, hi);
quicksort.call(this, lo, p - 1);
quicksort.call(this, p + 1, hi);
}
}
function partition(lo, hi) {
var pivot = this[hi],j=lo;
for (i=lo; i < hi;i++) {
if (this[i] <= pivot){
swap.call(this, i, j);
}
}
swap.call(this, i, hi);
return i;
}
function swap(a,b,c){
c = this[a];
this[a] = this[b];
this[b] = c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment