Skip to content

Instantly share code, notes, and snippets.

@Sammons
Created August 5, 2014 02:53
Show Gist options
  • Save Sammons/dc369fefd5748930f86e to your computer and use it in GitHub Desktop.
Save Sammons/dc369fefd5748930f86e to your computer and use it in GitHub Desktop.
quicksort.js
function quicksort( array, comparator ) {
var recur = function(left, right) {
if (left < right) {
var par = partition( left, right )
recur( left, par - 1 )
recur( par + 1, right )
}
}
var choose_pivot = function( left, right ) {
var len_min_1 = right - left
return left + Math.floor( Math.random() * len_min_1 )
}
var partition = function( left, right) {
var piv = choose_pivot( left, right )
piv_val = array[ piv ]
swap( piv, right )
var store = left
for (var i = left; i < right; i++) {
if ( comparator( array[i], piv_val) ) continue;
swap( i, store )
store++
}
swap( store, right )
return store;
}
var swap = function( that, with_this ) {
var tmp = array[ that ]
array[ that ] = array[ with_this ]
array[ with_this ] = tmp
}
recur(0, array.length - 1)
return array;
}
var ar = []
for (var i = 0; i < 100; i++) ar.push(Math.floor(Math.random()*100 ))
quicksort(ar,function(a,b) {
return a > b;
})
console.log(ar)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment