I have tried the entire day, and can't seem to be able to find out why it is not working. I think that the problem is my skills with JavaScript language. I might be missing some concept on parameter passing. Can you please show me where is the error?
Here is my implementation, based on another implementation I wrote a year ago in C#, which can be found here.
So here is the code (you can try direct on Chromes console, just copy/paste and it will "work"):
function merge(A, p, q, r){
var n1 = q - p + 1;
var n2 = r - q;
var i = 0;
var j = 0;
var L = [];
while (i < n1){
L.push(A[p + i++]);
}
var R = [];
while(j < n2){
R.push(A[q + j++ + 1]);
}
L.push(Number.MAX_VALUE);
R.push(Number.MAX_VALUE);
i = 0;
j = 0;
var k = p;
while(k <= r){
if(L[i] <= R[i]){
A[k] = L[i];
i = i + 1;
}else{
A[k] = R[j];
j = j + 1;
}
k = k + 1;
}
}
function mergeSort(A, p, r){
console.log(A);
if(p < r){
var q = Math.floor((p + r) / 2);
mergeSort(A, p, q);
mergeSort(A, q + 1, r);
merge(A, p, q, r);
}
}
function testMergeSort(array){
var p = 0;
var r = array.length - 1;
console.log("BEFORE: " + array);
mergeSort(array, p, r);
console.log("AFTER: " + array);
console.log("---------------------------------");
}
testMergeSort([5, 2, 4, 7, 1, 3, 2, 6]);