Merge Sort Algorithm Error
Oct 8, 2013 at 7:50pm UTC
This code comes strictly out of my textbook which is where my professor told us to copy the algorithm from. I've run into this error:
Unhandled exception at 0x00e81bc2 in Sort.exe: 0xC0000005: Access violation writing location 0x004d6000.
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 49 50 51 52
// merge_Sort Function Overload Definition 1
void Sort::merge_Sort(int Array[], int size)
{
int size1;
int size2;
if (size > 1)
{
size1 = size/2;
size2 = size - size1;
// Recursive Call overloaded merge_Sort Function
merge_Sort(Array, size1);
merge_Sort((Array +1), size2);
// Call 2nd Overloaded Function
merge(Array, size1, size2);
}
}
// merge_Sort Overloaded Function Definition 2
void Sort::merge(int Array [], int size1, int size2)
{
int * temp;
int copied = 0;
int copied1 = 0;
int copied2 = 0;
int i = 0;
temp = new int [size1+size2];
while ((copied1 < size1) && (copied2 < size2))
{
if (Array[copied1] < (Array + size1)[copied2])
{
temp[copied++] = Array[copied1++];
}
else
{
//ERROR HERE--> temp[copied++] = (Array + size1)[copied2];
}
}
while (copied1 < size1)
{
temp[copied++] = Array[copied1++];
}
while (copied2 < size2)
{
temp[copied++] = (Array + size1)[copied2++];
}
for (i; i < (size1+size2); ++i)
{
Array[i] = temp[i];
}
delete [] temp;
}
This is how I'm calling it in my Driver[UPDATED]:
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
Sort sort1(1000);
sort1.set_Seed(0);
sort1.initialize_Array();
clock_t start1 = clock();
for (int i = 0; i < N; i++)
{
sort1.insertion_Sort();
}
clock_t end1 = clock();
clock_t diff1= end1 - start1;
cout<<"\nIt takes the Insertion Sort " <<((diff1/(N*CLOCKS_PER_SEC))*THOUSAND)<<" milliseconds." ;
Sort sort2(1000);
sort2.set_Seed(0);
sort2.initialize_Array();
clock_t start2 = clock();
for (int i = 0; i < N; i++)
{
sort2.selection_Sort();
}
clock_t end2 = clock();
clock_t diff2= end2 - start2;
cout<<"\nIt takes the Selection Sort " <<((diff2/(N*CLOCKS_PER_SEC))*THOUSAND)<<" milliseconds." ;
Sort sort3(1000);
sort3.set_Seed(0);
sort3.initialize_Array();
clock_t start3 = clock();
for (int i = 0; i < N; i++)
{
//--> sort3.merge_Sort();
}
clock_t end3 = clock();
clock_t diff3= end3 - start3;
cout<<"\nIt takes the Insertion Sort " <<((diff3/(N*CLOCKS_PER_SEC))*THOUSAND)<<" milliseconds." ;
Last edited on Oct 8, 2013 at 7:54pm UTC
Oct 8, 2013 at 8:06pm UTC
Forgot the ++ on this
temp[copied++] = (Array + size1)[copied2++] // ++ was needed after copied2
FACE PALM!!
Topic archived. No new replies allowed.