我需要建立在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;
}
}
}
哦謝謝編輯,錯字。 – user1880760
至於segfault - 如何在調試器中運行它? – peterph