Search code examples
javaalgorithmsortingmergesortsentinel

Merge sort implementation questions in Java


I'm in an algorithms course and am learning about merge sort. Our professor recommended we try to implement the pseudo code provided in the book.

  1. Am I correct in using Integer.MAX_VALUE as a sentinel value when sorting an array of integers (used in lines 8 & 9 in the Merge method pseudo code below)?
  2. For line 2 of the Merge-Sort pseudo code method, is it correct to code that in Java using Math.ceil() like I did? (Edit: It's actually floor and I updated my code to reflect this.)

If you see any other mistakes please let me know!

Here is the pseudo code the book gives for merge sort. merge sort algorithm part 1

merge sort algorithm part 2

And, here is how I coded it in Java:

public void mergeSort(int[] arrNums, int p, int r) {
    if (p < r) {
        int q = (p + r) / 2;
        mergeSort(arrNums, p, q);
        mergeSort(arrNums, q + 1, r);
        merge(arrNums, p, q, r);
    }
}

public void merge(int[] arrNums, int p, int q, int r) {
    int nOne = q - p + 1;
    int nTwo = r - q;

    int[] arrLeft = new int[nOne + 1];
    int[] arrRight = new int[nTwo + 1];

    for (int i = 0; i < nOne; i++) {
        arrLeft[i] = arrNums[p + i - 1];
    }

    for (int j = 0; j < nTwo; j++) {
        arrRight[j] = arrNums[q + j];
    }

    arrLeft[nOne] = Integer.MAX_VALUE;
    arrRight[nTwo] = Integer.MAX_VALUE;

    // Tracks arrLeft index
    int i = 0;

    // Tracks arrRight index
    int j = 0;

    for (int k = p; k < r; k++) {
        if (arrLeft[i] <= arrRight[j]) {
            arrNums[k] = arrLeft[i];
            i++;
        } else {
            arrNums[k] = arrRight[j];
            j++;
        }
    }
}

Solution

  • The last for loop in your merge method, variable k should start from p - 1:

    for (int k = p - 1; k < r; k++) {
        if (arrLeft[i] <= arrRight[j]) {
            arrNums[k] = arrLeft[i];
            i++;
        } else {
            arrNums[k] = arrRight[j];
            j++;
        }
    }
    

    Pseudo code in many text books likes to start array index from 1, so here you need to subtract it by 1.