0

Hey everyone. Im having some problems with mergesort. Im supposed to run the mergesort function then print to a file. It's not printing.. Can someone show me where im going wrong?

This is the part of my switch statement that calls mergesort

case 3:
                //Sort array using Mergesort
                mergeSort( data, 1, MAXSIZE );
                //Print to outfile "lab07_mergesort.txt"
                printArray( data, MAXSIZE );
                //Inform user of successful mergesort
                cout << "The data has been sorted using Mergesort and" << endl;
                cout << "printed to file  lab7_mergeout.txt." << endl;
                break;

and these are my functions:

//Function printArray
void printArray( float array[], int SIZE )
{
    for( int i = 0; i < SIZE; ++i )
        bubbleoutfile << array[i] << " " ;
}

//Function mergeSort
void mergeSort(float array[], int start, int end)
{
    int n = end - start + 1; 
    if (n > 1)
    {
        int n1 = n / 2;
        
        mergeSort(array, start, start + n1 - 1);
        mergeSort(array, start + n1, end);
        
        float *tmp = new float[ end - start + 1 ];
        float *dest = tmp, 
        *src1 = array + start, 
        *src2 = array + start + n1;
        while ((src1 < array + start + n1) && (src2 <= array + end))
        {
            if (*src1 <= *src2)
                *dest++ = *src1++;
            else
                *dest++ = *src2++;
        }
        
        while (src1 <  array + start + n1 ) 
            *dest++ = *src1++;
        while (src2 <= array + end)
            *dest++ = *src2++;
        
        memcpy( array + start, tmp, n*sizeof(int) );
        delete[] tmp;
    }
}

Thanks in advance.

2
Contributors
1
Reply
2
Views
10 Years
Discussion Span
Last Post by Ancient Dragon
0

program has 2 problems. After fixing them your program runs ok without error.

1. // memcpy( array + start, tmp, n*sizeof(int) );
should be sizeof(float), not int

2. you didn't post main(), so I created my own. it has to pass one less than the number of elements in the array to function mergeSort().

int main()
{

	float array[] = {5,2,1,14,25,36,99,30,20,10,4,3};
	int SIZE = sizeof(array)/sizeof(array[0]);
	mergeSort(array, 0,SIZE-1);
	printArray( array, SIZE);

	return 0;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.