Advertisement

C++ Merge sort is duplicating data

Started by September 23, 2013 11:02 PM
2 comments, last by ApochPiQ 11 years, 4 months ago

I've been trying to get a merge sort to fix character arrays for a week now, and I cannot figure out for the life of me why I am getting half way sorted and then it just doubles everything. Here's what I have so far:


#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <stdlib.h>
#include <dos.h>
#include <time.h>
#include <sys/timeb.h>

using namespace std;

void MyMergeSort(int sourceArray[], int destinationArray[], int low, int high)
{
	if (low != high)
	{
		int middle = (low+high)/2;
		MyMergeSort(destinationArray, sourceArray, low, middle);
		MyMergeSort(destinationArray, sourceArray, middle+1, high);
		cout << "Merged: " << low << ", " << middle << " with " << middle+1 << ", " << high << endl;
		int start1 = low;
		int end1 = middle;
		int start2 = middle+1;
		int end2 = high;
		int destinationCount = 0;
		while ((start1 <= end1) && (start2 <= end2))
		{
			if(sourceArray[start1] < sourceArray[start2])
			{
				destinationArray[destinationCount] = sourceArray[start1];
				start1++;
			}
			else
			{
				destinationArray[destinationCount] = sourceArray[start2];
				start2++;
			}
			destinationCount++;
		}
		for(; start1 <= end1; start1++, destinationCount++)
		{
				destinationArray[destinationCount] = sourceArray[start1];
				cout << "in for loop start1" << endl;
		}
		for(; start2 <= end2; start2++, destinationCount++)
		{
			destinationArray[destinationCount] = sourceArray[start2];
			cout << "in for loop start2" << endl;
		}
	}
}

void main()
{
	int samplearray[10] ={10, 20, 30, 40, 50, 5, 6, 7, 35, 38};
	int copyarray[10];
	for (int x = 0; x < 10; x++)
	{
		copyarray[x] = samplearray[x];
	}
	
	MyMergeSort(copyarray, samplearray, 0, 9);
	cout << "Sample Array Contents:" << endl;
	for (int x = 0; x < 10; x++)
	{
		cout << samplearray[x] << " ";
	};
	cout << endl << endl;
	cout << "Copy Array Contents:" << endl;
	for (int x = 0; x < 10; x++)
	{
		cout << copyarray[x] << " ";
	};
	
   for (int z=start;z<=finish;z++)
   {
	   cout << MyArray[z] << "  ";
   }
   */
	int hold;
	cin >> hold;
}
Is there a particular reason not to just use std::merge?

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

Advertisement

It's an assignment. Sorry, I forgot to mention. I don't want a solution... I just want to know why my data is duplicating.

Step through it in a debugger.

Generally it is frowned upon to ask for homework help in these forums. If you can't solve the problem yourself using a debugger, I would recommend talking to your teacher or possibly other students for advice.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

This topic is closed to new replies.

Advertisement