Created
March 20, 2015 04:25
-
-
Save akilism/7e04b84cb4e66eec0476 to your computer and use it in GitHub Desktop.
quicksort js
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
var quickSort = (function(){ | |
var items; | |
var less = function(a, b) { return compare(items[a], items[b]) < 0; }; | |
var sort = function(items, lo, high) { | |
if(high <= lo) { return; } | |
mid = partition(items, high, lo); | |
sort(items, lo, mid-1); | |
sort(items, mid+1, high); | |
}; | |
var exch = function(a, i, j) { | |
var x = a[i]; | |
a[i] = a[j]; | |
a[j] = x; | |
}; | |
var compare = function(valA, valB) { | |
if(valA > valB) { return 1; } | |
if(valA === valB) { return 0; } | |
if(valA < valB) { return -1; } | |
}; | |
var partition = function(items, high, lo) { | |
var i = lo; | |
var j = high + 1; | |
while(true) { | |
while(less(++i, lo)) { if(i === high) { break; } } | |
while(less(lo, --j)) { if(j === lo) { break; } } | |
if(i >= j) { break; } | |
exch(items, i, j); | |
} | |
exch(items, lo, j); | |
return j; | |
}; | |
var shuffle = function(arr) { | |
var len = arr.length; | |
for(var i = len - 1; i > 0; i--) { | |
var j = Math.round(Math.random() * i); | |
var hole = arr[i]; | |
arr[i] = arr[j]; | |
arr[j] = hole; | |
} | |
return arr; | |
}; | |
return { | |
sort: function(arr) { | |
items = shuffle(arr); | |
sort(items, 0, items.length-1); | |
} | |
}; | |
})(); | |
var arr = ['j','a','k','b','e','h','f','d','i','c','g']; | |
quickSort.sort(arr); | |
console.log(arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment