I am trying to do merge sort using void*
. If I keep numbers I want to sort to 1-byte it works perfectly. However if the number is located in more than 1 byte it doesn't work well. I believe it takes it as 2 numbers. I tested it with number 500 and at the end I have 256 and 244 not sorted ....
#include "msort.h"
#include <iostream>
using namespace std;
void Mergesort( void* base, size_t nelem, size_t width,
int (*fcmp)( const void*, const void* ) )
{
if (nelem <=1)
return;
int lhsnelem = nelem/2;
int rhsnelem = nelem - lhsnelem;
char* midpoint = (char*)(base) + ((nelem/2)*width);
cout << "width is: " << width << endl;
Mergesort(base, lhsnelem, width, fcmp);
Mergesort(midpoint, rhsnelem, width, fcmp);
//ItemType* temp= new ItemType[nelem];
int temp[20];
char* lhs = (char*)(base);
char* rhs = midpoint;
char* end = rhs + (rhsnelem*width);
int count = 0;
while ((lhs != midpoint) && (rhs != end))
{
int num = fcmp( lhs, rhs );
if (num <= 0)
{
temp[count] = *lhs;
lhs = lhs + width;
}
else
{
temp[count] = *rhs;
rhs = rhs + width;
}
count++;
}
if (lhs == midpoint)
{
while (rhs != end)
{
temp[count] = *rhs;
rhs = rhs + width;
count++;
}
}
else
{
while (lhs != midpoint)
{
temp[count] = *lhs;
lhs = lhs + width;
count++;
}
}
for (int i=0; i<nelem; i++)
{
lhs = (char*)(base)+ (width*i);
*lhs = temp[i];
lhs = lhs + width;
}
}
main.cpp
/////// main.cpp ///////////////////////
// here is my comparison function in main.cpp
int compare(const void *one, const void *two)
{
if (*(int*)one > *(int*)two) return 1;
if (*(int*)one < *(int*)two) return -1;
return 0;
}
The output for 1-byte numbers is OK:
In: 5 8 7 4 1 6 11 41 160 47 38 120 40 58 12 43 66 98 17 140
Out: 1 4 5 6 7 8 11 12 17 38 40 41 43 47 58 66 98 120 140 160
The output if there is a 2-byte number is not OK the sorting doesn't work well:
In: 500 50 8 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Out: 256 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 50 244