//对数组中的元素按堆排序
void sift(void* a, int esize,int i, int n,int(*cmp)(void *,void*,void *),void *param,void *tmp){
int child;memcpy(tmp,(char*)a+esize*i,esize);
while(n >= 2 * (i+1)){
child = 2 * (i+1);
if (child < n && cmp((char*)a+child*esize, (char*)a+(child-1)*esize,param)>0){
child++;
}
if (cmp(tmp,(char*)a+(child-1)*esize,param)<0){
memcpy((char*)a+esize*i,(char*)a+esize*(child-1),esize);
}
else break;
i = child-1;
}
memcpy((char*)a+i*esize,tmp,esize);
}
void heap_sort(void *array,int element_size,int element_num,int(*cmp)(void *,void*,void *),void *param){
int i;
void *tmp=malloc(element_size);
for (i = (element_num-1) / 2; i >= 0; i--){
sift(array,element_size, i, element_num,cmp,param,tmp);
}
for (i = element_num-1; i >= 0; i--){
memcpy(tmp,array,element_size);
memcpy(array,(char*)array+element_size*i,element_size);
memcpy((char*)array+element_size*i,tmp,element_size);
sift(array, element_size,0, i,cmp,param,tmp);
}
free(tmp);
}
int cmp(void *a,void *b,void *p){
return *(int*)a-*(int*)b;
}
int main(){
int a[]={1,4,100,6,3,0,2,-1};
int i;
heap_sort(a,sizeof(int),sizeof(a)/sizeof(int),cmp,NULL);
for(i=0;i<sizeof(a)/sizeof(int);i++){
printf("%d ",a[i]);
}
printf("\n");
}