Skip to content

Instantly share code, notes, and snippets.

@antoniopicone
Last active October 17, 2017 14:10
Show Gist options
  • Save antoniopicone/47ab0c3063023fce590a991b11f26202 to your computer and use it in GitHub Desktop.
Save antoniopicone/47ab0c3063023fce590a991b11f26202 to your computer and use it in GitHub Desktop.
var merge = function(A,p,q,r) {
// 1, 4 , 9, intervalli da [1..4] incluso, [5...9]
var n1 = q - p +1; // = 4 -1 +1 = 4
var n2 = r - q; // 5
var L = [], R = [];
for(var i=1; i<=n1;i++) { // da 1 a 4
L[i] = A[p + i - 1]; // setta L[i] = A[1+1-1]= 6, L[1+2-1]=L[2]=7, L[1+3-1]=L[3]=8, L[1 + 4 -1]=L[4] = 9
}
for (var j=1;j<=n2;j++) { // da 1 a 5
R[j] = A[q + j] ; // setta R[1] = A[4+1]=1, ..., R[n2]=R[5]=A[9]=5
}
L[n1+1] = 9999;
R[n2+1] = 9999;
i=1;
j=1;
for (var k=p;k<=r;k++) {
// console.log('confronto: '+L[i]+' con '+R[j]);
if(L[i]<R[j]) {
A[k] = L[i];
i++;
}
else {
A[k] = R[j];
j++;
}
}
return A;
}
var ar=[null,6,7,8,9,1,2,3,4,5];
console.log(merge(ar,1,4,9));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment