Comparison Count Merge Sort

Oct 24, 2010 at 9:59pm
I am having trouble counting comparisons using recursion with Merge Sort. I haven't even studied recursion yet but get the gist of it somewhat. I am getting 31 compares on a list of 32 ints using merge sort, I know it shouldn't be that high or is it?. What am I doing wrong? Here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
int mergeSort(long array[], int begin, int end)
{
    int middle, iCompareOut = 0;

    if (begin < end)
    {
        middle = (begin + end) / 2;        // calculate middle position
        mergeSort(array, begin, middle);   // recursive call with 1st half of array
        mergeSort(array, middle + 1, end); // recursive call with 2nd half of array
        
        // merge the 2nd half into the 1st half of array
        iCompareOut = merge(array, begin, middle, end);  
    }
    return iCompareOut;
}

int merge(long array[], int low, int mid, int high)
{
    int i = low,     // holds low start position in array
        j = mid + 1, // holds 2nd start position in array
        k = low,     // holds low position in 2nd dynamic array
        iCompareIn = 0;
        
    // dynamically create array to hold temp array 
    long * array_temp = new long[high + 1];

    while (i <= mid && j <= high) // doesn't let either position run into their max
    {
        if (array[i] < array[j])  // verify low is still < middle
            array_temp[k++] = array[i++]; // assign to temp array and increment
        else                              
            array_temp[k++] = array[j++]; // assign to temp array and increment
        iCompareIn++;
    }
    // finish filling the temp array after conditions cannot be met above
    while (i <= mid)     // if low is not yet to middle
        array_temp[k++] = array[i++];    // assign to temp array and increment

    while (j <= high)    // if mid is not yet to high                
        array_temp[k++] = array[j++];     // assign to temp array and 
    
    for (i = low; i < k; i++)  // copy the array back into original
        array[i] = array_temp[i];         
    
    free(array_temp);  // return memory no longer used
    
    return iCompareIn;
Last edited on Oct 24, 2010 at 10:39pm
Topic archived. No new replies allowed.