Last active
November 29, 2017 13:11
-
-
Save iegik/73df8db69a2b7420ae4ae1ec240b888d to your computer and use it in GitHub Desktop.
Quick Sort
This file contains hidden or 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
var a = [5,3,7,1,10,-1]; | |
quicksort.call(a); | |
console.log(a); // -1, 1, 3, 5, 7, 10 |
This file contains hidden or 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
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