//  MERGE-SORT ROUTINE 

void merge_sort(int A[], int B[], int l, int r, int &lc) {
  int i,j,bptr,mid;

  lc++;  if (l == r) return;
  mid = (l + r)/2; lc++;
  merge_sort(A,B,l,mid,lc); lc++;
  merge_sort(A,B,mid+1,r,lc); lc++;

//  Now merge the 2 halves of A, until reaching the end of one

  i = bptr = l; lc++;
  j = mid+1; lc++;
  while (i <= mid && j <= r){
    lc++;
    if (A[i] <= A[j]) {
      lc++;
      B[bptr] = A[i]; lc++;
      i++; lc++;
    }
    else {
      lc++;
      B[bptr] = A[j]; lc++;
      j++; lc++;
    }
    bptr++; lc++;
  }

//  If there are any elements from the left half, copy them to the B array

  while (i <= mid) {
     lc++;
     B[bptr] = A[i]; i++; bptr++; lc++;
     }

// Now copy B back into A (except those that we know are already there)

  for (int k=l; k <= j-1; k++){
     lc++;
     A[k] = B[k]; lc++;
   }

  lc++;
  return;
}

   

