Javascript Algorithm Array Sort Merge Sort 4
function merge(left,right){ var i = 0; /* left partition index */ var j = 0; /* right partition index */ var l = left.length + right.length; var k = 0;/*from ww w . ja v a2s. c o m*/ var a = []; /* add sentinel values to the array */ left.push(Number.MAX_VALUE); right.push(Number.MAX_VALUE); for( k=0; k<l;k+=1 ){ /* takes the element from the left array */ if( left[i]<=right[j] ){ a.push( left[i] ); i +=1; /* takes the element from the right array */ }else{ a.push( right[j] ); j +=1; } } return a; } function mergeSort(a){ var q = 0, l = 0, left,right; l = a.length; if( l < 2 ){ return a; } q = Math.floor(l/2); left = mergeSort(a.slice(0,q)); right = mergeSort(a.slice(q,l)); a = merge( left , right ) return a; } var arr = [1,245,1,5,13,-1,-56,1235,-187,5,8,0,11,45]; arr = mergeSort( arr , 0 , arr.length ); console.log(arr);