Hi,

I have written a generic mergesort program which is as below:

---------------------------------------------------------

mergesort.h

-----------------------

void

MergeSort(void *array[],int p,int r,int elemSize,int(*Compare)(const

void *keyA,const void *keyB));

void

Merge(void *array[],int p,int q, int r,int elemSize,int(*Compare)(const

void *keyA,const void *keyB));

int

IntegerComp(const void *keyA,const void *keyB);

mergesort.c

--------------------

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include "mergesort.h"

void

MergeSort(void *array[],int p,int r,int elemSize,int(*Compare)(const

void *keyA,const void *keyB))

{

int q;

if(p < r) {

q = (p + r)/2;

MergeSort(array,p,q,elemSize,Compare);

MergeSort(array,q + 1,r,elemSize,Compare);

Merge(array,p,q,r,elemSize,Compare);

}

}

void

Merge(void *array[],int p,int q, int r,int elemSize,int(*Compare)(const

void *keyA,const void *keyB))

{

void **out = (void **)malloc(elemSize * r);

int i,k,j;

i = k = p;

j = q + 1;

while( i <= q && j <= r ) {

if( Compare( &array[i * elemSize],&array[j * elemSize] ) <= 0 ) {

out[k++] = array[i++];

} else {

out[k++] = array[j++];

}

}

while( i <= q ) out[k++] = array[i++];

while( j <= r ) out[k++] = array[j++];

for (i = p;i < r; i++) {

array[i] = out[i];

}

free(out);

}

int

IntegerComp(const void *keyA,const void *keyB)

{

if( (const int *) keyA == (const int *) keyB ) return 0;

else if( (const int *) keyA < (const int *) keyB ) return -1;

else if( (const int *) keyA (const int *) keyB ) return 1;

}

----------------------------------------------

And the driver program is here:

test.c

---------

#include <stdio.h>

#include "mergesort.h"

int

main()

{

int idx,length;

int arr[] = { 2,21,1,48,15,31,26 };

length = sizeof arr/sizeof &arr[0];

printf("Before sorting array:\n");

for (idx = 0;idx < length;idx++)

{

printf("%d ",arr[idx]);

}

printf("\n");

MergeSort(&arr,0,length,sizeof(int),IntegerComp);

printf("After sorting array:\n");

for (idx = 0;idx < length;idx++)

{

printf("%d ",arr[idx]);

}

printf("\n");

return 0;

}

----------------------------------------------------------

I compile the programs above as:

gcc -g -o mergesort mergesort.c test.c

The output is little surprising as the array looks unsorted after sort

algorithm is completed. I am not understanding what's going wrong here,

kindly help me.:

kalyan@proteus mergesort

Before sorting array:

2 21 1 48 15 31 26

After sorting array:

2 21 1 48 15 31 26

Thank you.

Regards

Kalyan