Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding how merge sort works

private void merge(int[] array, int[] aux, int low, int mid, int hi) {
    int i = low, j = mid + 1, k;

    for (k = low; k <= hi; k++) {
        aux[k] = array[k];
    }
    for (k = low; k <= hi; k++) {
        if (i > mid) {
            array[k] = aux[j++];
        } else if (j > hi) {
            array[k] = aux[i++];
        } else if (aux[j] <  aux[i]) {
            array[k] = aux[j++];
        } else /* if (aux[i] <= aux[j] */ {
            array[k] = aux[i++];
        }
    }
}

private void sort(int[] array, int[] aux, int lo, int hi) {   
    if (hi <= lo) {
        return;
    }

    int mid = lo + (hi - lo) / 2;
    sort(array, aux, lo, mid);
    sort(array, aux, mid + 1, hi);
    merge(array, aux, lo, mid, hi);
}

public void mergeSort() {      
    int aux[] = new int[n];
    sort(ar, aux, 0, n - 1);
}

The code works but I'm having trouble to understand it.

  1. I understand the purpose of

    if (hi <= lo) {
        return;
    }
    

    but I do not know what happens when return is executed.

  2. I do not understand why the last else in the merge function exists. If the algorithm is splitting up until aux is [3,5] and I want to sort ascending, the else if will compare 5 < 3 which will jump to the else and it should exchange the 2 values.

Edit: I played a bit with the debugger and for this example (3 33 1 55 66 34 67 45 23) it reaches the merge function with the first 2 values . The last else if compares 33 < 3 and enters the last else .If these values are in the correct order what is the point of this line of code? After array[k] = aux[i++]; is executed the value of array[0] is the same which is odd because aux[i++] is array[1]

like image 492
Adrian.I Avatar asked Oct 19 '22 06:10

Adrian.I


1 Answers

  1. In the sort method the problem is divided in smaller sub-problems. When the range to sort is only one or zero wide there is nothing to do and the method can be closed. That is because one element alone is sorted by definition. It is the stop condition of the recursion like m0skit0 said.

  2. Elements are not swapped in this algorithm. The method trys to merge two sorted arrays. There are two indices i and j. When i reaches the middle, all elements in the right part are added to the result array. If j reaches the right border, all elements of the left part are added to the result. That are the first two cases.
    Now in the two last cases the algorithm tries to figure out which of the current elements indexed by i and j is the minimum and adds it to the result array. In the third case the element at j is smaller and added to the result array. In the forth case the element at i is selected.

like image 96
TheSlater Avatar answered Nov 04 '22 22:11

TheSlater