0

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.

Robomatt
  • 35
  • 4
  • Not entirely sure (I'm new to c++), but maybe upon calling the method, it already reserved `int i` on the stack. This contains a bogus value until it's assigned a proper value. http://stackoverflow.com/questions/6247017/unexplained-c-default-int-values – Caramiriel Jan 02 '15 at 13:00

1 Answers1

0

"-858993460 is, in hex, CCCCCCCC, which Visual Studio puts as default in DEBUG MODE." It is when you don't initialize a variable.

Read this answer : https://stackoverflow.com/a/6247048/2696576

Community
  • 1
  • 1
Abhishek Gupta
  • 1,297
  • 13
  • 28