我需要在 C 中创建一个“通用”堆排序。
我有一个包含比较功能的主文件。本质上,数组的基地址、元素数量、每个元素的大小和比较函数都传递给堆排序函数。我遇到了两个问题,一个是程序没有对其进行排序,所以我想知道是否有人能看出代码有什么问题。两个我在 1710 个元素后遇到分段错误。
#include <stdio.h>
#include <string.h>
#include "srt.h"
void srtheap(void *, size_t, size_t, int (*)(const void *, const void *));
void heapify(void *, size_t, size_t, size_t, int (*)(const void *, const void *));
void srtheap(void *base, size_t nelem, size_t size, int (*compar)(const void *, const void *)) {
char *p1, *p2;
char *qb=base;
void *last = qb + (size*(nelem-1));
for (size_t curpos = nelem-1; curpos>0; curpos=-2){
p1 = qb + ((curpos-1)/2)*size;
if(compar(last, (last-size)) >= 0){
if(compar(last, p1) > 0){
swap(last, p1, size);
heapify(qb, nelem, curpos, size, compar);
}
}
else { //LEFT>RIGHT
if(compar(last-size, p1) > 0){
swap(last-size, p1, size);
heapify(qb, nelem, curpos-1, size, compar);
}
//otherwise, parent is greater than LEFT & RIGHT,
//or parent has swapped with child, iteration done, repeat through loop
} //end else, children have been compared to parent
//end check for two children, only left child if this loop is skipped
last = last-(2*size);
}
/*
**Now heapify and sort array
*/
while(nelem > 0){
last = qb + (size*(nelem-1));
swap(qb, last, size);
nelem=nelem-1;
heapify(qb, nelem, 0, size, compar); //pass in array, #elements, starting pos, compare
}
}
void heapify(void *root, size_t numel, size_t pos, size_t sz, int (*compar)(const void *, const void *)){
void *rc, *lc, *p1;
while(pos < numel){
rc = root+((pos+1)*2)*sz; //right child
lc = root+(((pos+1)*2)-1)*sz; //left child
p1 = root+(pos*sz); //parent
if((pos+1)*2 < numel){ //check if current element has RIGHT
if (compar(rc, lc)>=0){
if(compar(rc, p1)>0) {
swap(rc, p1, sz);
pos=(pos+1)*2; //move to RIGHT, heapify
}
else {
pos = numel; //PARENT>LEFT&RIGHT, array is heapified for now
}
} //end RIGHT>LEFT
else { //LEFT>RIGHT
if(compar(lc, p1) >0 ) {
swap(lc, rc, sz);
pos=((pos+1)*2)-1; // move to LEFT, heapify
}
else {
pos = numel; //PARENT>LEFT&RIGHT, array is heapified for now
} //end inner if, else
}//end LEFT,RIGHT comparison
}//end check for RIGHT
else if (((pos+1)*2)-1 < numel){ //else, check if element has LEFT
if(compar(lc, p1)>0){
swap(lc, p1, sz);
pos=((pos+1)*2)-1; //move to LEFT, continue heapify
}
else {
pos = numel; //PARENT>LEFT, array is heapified for now
}
}//end check for LEFT
else { //current element has no children, array is heapified for now
pos = numel;
}
}
}