I am trying to understand a Merge Sort algorithm. I am going through it step by step. Here is my code:
Edit: I also added the recursive function below. The problem is at the merge function.
void mergeSort(vector<int>& arr, int size, int low, int high)
{
if (low < high) {
int middle = (low + high) / 2;
mergeSort(arr, size, low, middle);
mergeSort(arr, size, middle + 1, high);
merge(arr, size, low, middle, high);
}
}
void merge(vector<int>& arr, int size, int low, int middle, int high)
{
int* temp = new int[size];
for (int i = low; i<high; i++)
temp[i] = arr[i];
int i = low;
int j = middle + 1;
int k = low;
while (i <= middle && j <= high) {
if (temp[i] <= temp[j]) {
arr[k] = temp[i];
i++;
}
else {
arr[k] = temp[j];
j++;
}
k++;
}
while (i <= middle) {
arr[k] = temp[i];
k++;
i++;
}
delete[] temp;
temp = NULL;
}
The parameters to the 'merge' function are an array of size = 10, low = 0, middle = 0, and high = 1. After the first line, creating the dynamic array, an 'i' variable pops up with a bizarre value of -858993460. After the for loop, it becomes 1. After the line, int i = low; I stays at value 1 and it is not equal to the value of low, which is zero. How is this possible? I am eating my brains out here. Thanks.