#include <iostream> #include <stdlib.h> using namespace std; int compared(const void *key1,const void *key2) { //cout<<"enter compare"<<endl; const int* iKey1 = (int*)key1; const int* iKey2 = (int*)key2; //cout<<*iKey1<<endl; //cout<<*iKey2<<endl; if(*iKey1>*iKey2){ //cout<<"big"<<endl; return 1; } else if(*iKey1==*iKey2){ //cout<<"equal"<<endl; return 0; } else if(*iKey1<*iKey2) { //cout<<"less"<<endl; return -1; } } //k设置为size-1 //i设置为0 //j设置为中间数 static int merge(void* data, int esize, int i, int j, int k, int (*compare) (const void* key1,const void* key2)) { char *a = (char*)data, *m=NULL; int ipos, jpos, mpos; ipos = i; jpos = j+1; mpos = 0; if((m=(char*)malloc(esize*((k-i)+1)))==NULL ) { return -1; } while(ipos<=j||jpos<=k) { if(ipos>j) { //the left elements has no more elements to merge while(jpos<=k) { memcpy(&m[mpos*esize],&a[jpos*esize],esize); jpos++; mpos++; } continue; } else if(jpos>k) { //right division has no more elements to merge. while(ipos<=j) { memcpy(&m[mpos*esize],&a[ipos*esize],esize); ipos++; mpos++; } continue; } if(compare(&a[ipos*esize],&a[jpos*esize])<0) { memcpy(&m[mpos*esize],&a[ipos*esize],esize); ipos++; mpos++; } else { memcpy(&m[mpos*esize],&a[jpos*esize],esize); jpos++; mpos++; } } //prepare to merge data memcpy(&a[i*esize], m,esize*((k-1)+1)); free(m); return 0; } int mgsort(void *data, int size, int esize, int i,int k,int (*compare) (const void* key1,const void* key2)) { int j; //stop the recursion when no more element divisions can be made. if(i<k) { //determine where to divide the elements j = (int)(((i+k-1))/2); if(mgsort(data,size,esize,i,j,compared)<0) { return -1; } if(mgsort(data,size,esize,j+1,k,compared)<0) { return -1; } //merge the two sorted divisions into a single sorted set if(merge(data,esize,i,j,k,compared)<0) { return -1; } } return 0; } int main(int argc, char *argv[]) { int a[]={4,2,5,8,4,6}; for(int i=0;i<6;i++) { cout<<a[i]<<","; } cout<<endl; mgsort(a,6,4,0,5,compared); for(int i=0;i<6;i++) { cout<<a[i]<<","; } cout<<endl; system("PAUSE"); return 0; }