Skip to content

Instantly share code, notes, and snippets.

@pedrombafonso
Created May 29, 2013 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pedrombafonso/5668956 to your computer and use it in GitHub Desktop.
Save pedrombafonso/5668956 to your computer and use it in GitHub Desktop.
Quick sort Sorts JSON complex type arrays by property
function partition ( list, prop, begin, end, pivot ) {
var piv = list[pivot];
swap (list, pivot, end-1 );
var store = begin;
var ix;
for ( ix = begin; ix < end - 1; ++ix ) {
if ( list[ix][prop] <= piv[prop] ) {
swap (list, store, ix );
++store;
}
}
swap (list, end-1, store );
return store;
}
function swap (obj, a, b ) {
var tmp = obj[a];
obj[a] = obj[b];
obj[b] = tmp;
}
function qsort ( list, prop, begin, end ) {
if ( end - 1 > begin ) {
var pivot = begin + Math.floor ( Math.random () * ( end - begin ) );
pivot = partition ( list, prop, begin, end, pivot );
qsort ( list, prop, begin, pivot );
qsort ( list, prop, pivot + 1, end );
}
}
function quick_sort ( list, prop ) {
qsort ( list, prop, 0, list.length );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment