简体   繁体   中英

Merge Sort recursion In Java

I'm not sure how the recursion works in this method:

private void doMergeSort(int lowerIndex, int higherIndex) {

    if (lowerIndex < higherIndex) {
        int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
        // Below step sorts the left side of the array
        doMergeSort(lowerIndex, middle);
        // Below step sorts the right side of the array
        doMergeSort(middle + 1, higherIndex);
        // Now merge both sides
        mergeParts(lowerIndex, middle, higherIndex);
    }
}

lets say we have an array of index 8. The first middle value is set to 4, then the method recurs and the higher index is set to 4?

so it looks like this?

private void doMergeSort(int 0, int 4) {

    if (0 < 4) // condition is met {
        int middle = 0 + (4 - 0) / 2;
        // middle value is set to 2
        doMergeSort(lowerIndex, middle);
        // Below step sorts the right side of the array
        doMergeSort(middle + 1, higherIndex);
        // Now merge both sides
        mergeParts(lowerIndex, middle, higherIndex);
   }
}

No, you've not calculated the value of middle correctly for the first execution.

Given that the array has 8 elements, array's first index will be 0, and the last index will be 7.

   middle = lowerIndex + (higherIndex - lowerIndex) / 2;
          = 0 + (7 - 0) / 2
          = 0 + 7 / 2
          = 3. //remember the truncation in int.

Hence, the 2 calls would be:

  1. doMergeSort(0, 3)
  2. doMergeSort(4, 7)

And, your code for the first recursive call is shown below:

private void doMergeSort(int 0, int 3) {

  if (0 < 3) // condition is met {
    int middle = 0 + (3 - 0) / 2;
    // middle value is set to 1
    doMergeSort(lowerIndex, middle);
    // Below step sorts the right side of the array
    doMergeSort(middle + 1, higherIndex);
    // Now merge both sides
    mergeParts(lowerIndex, middle, higherIndex);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM