Javascript Algorithm Array Sort Quick Sort 2
function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function swap(a,i,j){ var tmp = a[i]; a[i] = a[j];// ww w. j a v a 2s .c o m a[j] = tmp; } function partition(a,left,right){ left = left ? left : 0; right = right ? right : a.length-1; var i = left+1, j = right, p = left; while( i<=j ){ while( a[i]<a[p] ){ i+=1; } while( a[j]>a[p] ){ j-=1; } if( i<j ){ swap(a,i,j); i+=1; j-=1; } } swap(a,p,j); return j; } function quicksort(a,left,right){ var k = 0, m = 0; left = left ? left : 0; right = right ? right : a.length-1; if( left<right ){ k = getRandomInt(left,right); swap(a,left,k); m = partition(a,left,right); quicksort(a,left,m-1); quicksort(a,m+1,right); } } var a = [-1,5,11,-124,6,7,1,3,99,987,55,24,12]; quicksort(a); console.log(a);