1

I was learning to merge sort an integer array, when I noticed that while copying the sorted array elements to the original array, we need two separate loop variables to run simultaneously, while the values at those indices are copied to the original array. Here is the code for reference:

class MergeSort {
public static void sort(int arr[], int si, int ei, int mid) {

    int merged[] = new int[ei - si + 1];
    int index1 = si; // tracks the first array
    int index2 = mid + 1; // tracks the second array
    int i = 0;
    while (index1 <= mid && index2 <= ei) {
        if (arr[index1] <= arr[index2]) {
            merged[i++] = arr[index1++];
        } else {
            merged[i++] = arr[index2++];
        }
    } // end of while

    while (index1 <= mid) {
        merged[i++] = arr[index1++];
    }

    while (index2 <= ei) {
        merged[i++] = arr[index2++];
    }
    // to copy merged[] to arr[] 
        
    int j = si;
    for (i = 0; i < merged.length; i++, j++) {
        arr[j] = merged[i];
    }
} // end sort()

public static void divide(int arr[], int si, int ei) {
    //  base case
    if (si >= ei) {
        return;
    } // end of base case

    int mid = si + (ei - si) / 2; // same as (ei-si)/2 but with less space complexity
    divide(arr, si, mid);
    divide(arr, mid + 1, ei);
    sort(arr, si, ei, mid);
} // end of divide

public static void main(String args[]) {
    int arr[] = { 1, 8, 0, 7, -4 };
    int n = arr.length;
    divide(arr, 0, n - 1);

    for (int i = 0; i < n; i++) {
        System.out.print(arr[i] + " ");
    } // end of for
} // end of main
} // end of class

Notice that while copying the values of the array merged[] to the array arr[], we are using two separate variables i and j. I did try using only one loop variable, which went like:

for (int i = 0; i < arr.length; i++) {
    arr[i] = merged[i];
}

but received an incorrect output. If anyone knows why we need two separate variables for the operation, please let me know. Thank you :)

chqrlie
  • 131,814
  • 10
  • 121
  • 189
  • You don't need two variables, that's just how that implementation has chosen to do it. Look at your single variable implementation. Do you see how it doesn't do the same thing as the original? – tgdavies Jun 07 '22 at 07:39
  • You're merging two lists, so there's one var to keep track of the separate indexes per list. The loops don't run simultaneously, exactly, they run one after the other. – ggorlen Jun 08 '22 at 15:44

1 Answers1

0

You could use a single variable in this final loop, but you must add the offset of the start of the slice in the destination array:

for (int i = 0; i < arr.length; i++) {
    arr[si + i] = merged[i];
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189