Search code examples
javarecursionnestedmergesort

What is the sequence of actions at a recursion?


I am trying to understand a merge sort algorithm java code but I really stuck at the splitting phase. Full code is here:

public class Main {

    public static void main(String[] args) {
        int[] intArray = { 20, 35, -15, 7, 55, 1, -22 };

        mergeSort(intArray, 0, intArray.length);

        for (int i = 0; i < intArray.length; i++) {
            System.out.println(intArray[i]);
        }
    }

    // { 20, 35, -15, 7, 55, 1, -22 }
    public static void mergeSort(int[] input, int start, int end) {

        if (end - start < 2) {
            return;
        }

        int mid = (start + end) / 2;
        mergeSort(input, start, mid);
        mergeSort(input, mid, end);
        merge(input, start, mid, end);
    }

    // { 20, 35, -15, 7, 55, 1, -22 }
    public static void merge(int[] input, int start, int mid, int end) {

        if (input[mid - 1] <= input[mid]) {
            return;
        }

        int i = start;
        int j = mid;
        int tempIndex = 0;

        int[] temp = new int[end - start];
        while (i < mid && j < end) {
            temp[tempIndex++] = input[i] <= input[j] ? input[i++] : input[j++];
        }

        System.arraycopy(input, i, input, start + tempIndex, mid - i);
        System.arraycopy(temp, 0, input, start, tempIndex);
    }
}

At the following mergeSort method:

public static void mergeSort(int[] input, int start, int end) {

    if (end - start < 2) {
        return;
    }

    int mid = (start + end) / 2;
    mergeSort(input, start, mid);
    mergeSort(input, mid, end);
    merge(input, start, mid, end);
}

there are two recursive calls to mergeSort and one merge call, so what is the sequence of actions at this method and how splitting could be done without any extra variables for keeping divided unsorted data?


Solution

  • Using [ ] to indicate splits, | | for single runs, { } for merged runs. This is the order:

                                            level of recursion
    [ 20   35  -15    7   55    1  -22]     0
    [ 20   35  -15]                         1
    | 20|                                   2
         [ 35  -15]                         2
         | 35|                              3
              |-15|                         3
         {-15   35}                         2
    {-15   20   35}                         1
                   [  7   55    1  -22]     1
                   [  7   55]               2
                   |  7|                    3
                        | 55|               3
                   {  7   55}               2
                             [  1  -22]     2
                             |  1|          3
                                  |-22|     3
                             {-22    1}     2
                   {-22    1    7   55}     1
    {-22  -15    1    7   20   35   55}     0