I am attempting to implement a recursive merge sort algorithm to sort a simple array of integers but I am getting weird values for the indexes in the second half of my array. The first half seems to sort fine which is confusing given that its implemented recursively. The array of random integers is initialized in my main method.

```
public class MergeSort {
public static int Rounds = 1;
public static void MergeSort(Comparable[] ToSort, Comparable[] temp, int first, int last) {
if(first < last) {
int mid = (first + last) / 2;
//Test Block
System.out.print("For Round " + Rounds + ":n");
System.out.print("first = " + first + " mid = " + mid + " last = " + last + "n");
Rounds++;
System.out.print("Array in Round " + (Rounds - 1) + " = {");
for(int i = 0; i <= ToSort.length - 1; i++) {
System.out.print(ToSort[i]);
if(i < ToSort.length - 1)
System.out.print(", ");
else {
System.out.print("}nn");
}
}
MergeSort(ToSort, temp, first, mid);
MergeSort(ToSort, temp, mid + 1, last);
Merge(ToSort, temp, first, mid + 1, last);
}
}
public static void Merge(Comparable[] ToSort, Comparable[] temp, int first, int mid, int last) {
int beginHalf1 = first;
int endHalf1 = mid - 1;
int beginHalf2 = mid;
int endHalf2 = last;
int index = first;
int Elements = (last - first) + 1;
while(beginHalf1 <= endHalf1 && beginHalf2 <= endHalf2) {
if(ToSort[beginHalf1].compareTo(ToSort[beginHalf2]) < 0) temp[index++] = ToSort[beginHalf1++];
else temp[index++] = ToSort[beginHalf2++];
}
while(beginHalf1 <= endHalf1) temp[index++] = ToSort[beginHalf1++];
while(beginHalf2 <= endHalf2) temp[index++] = ToSort[beginHalf2++];
for(int i = 0; i < Elements; i++, last--) ToSort[last] = temp[last];
}
```

}

This produces the following output:

UNSORTED ARRAY = {15, 9, 12, 19, 49, 43, 57, 70, 78, 87}

For Round 1:

first = 0 mid = 4 last = 9

Array in Round 1 = {15, 9, 12, 19, 49, 43, 57, 70, 78, 87}

For Round 2:

first = 0 mid = 2 last = 4

Array in Round 2 = {15, 9, 12, 19, 49, 43, 57, 70, 78, 87}

For Round 3:

first = 0 mid = 1 last = 2

Array in Round 3 = {15, 9, 12, 19, 49, 43, 57, 70, 78, 87}

For Round 4:

first = 0 mid = 0 last = 1

Array in Round 4 = {15, 9, 12, 19, 49, 43, 57, 70, 78, 87}

For Round 5:

first = 3 mid = 3 last = 4

Array in Round 5 = {9, 12, 15, 19, 49, 43, 57, 70, 78, 87}

For Round 6:

first = 5 mid = 7 last = 9

Array in Round 6 = {9, 12, 15, 19, 49, 43, 57, 70, 78, 87}

For Round 7:

first = 5 mid = 6 last = 7

Array in Round 7 = {9, 12, 15, 19, 49, 43, 57, 70, 78, 87}

For Round 8:

first = 5 mid = 5 last = 6

Array in Round 8 = {9, 12, 15, 19, 49, 43, 57, 70, 78, 87}

For Round 9:

first = 8 mid = 8 last = 9

Array in Round 9 = {9, 12, 15, 19, 49, 43, 57, 70, 78, 87}