c通用的heapsort

好吧所以我需要在c中创建一个’通用’heapsort,这就是我到目前为止(我可能在代码中缺少一些结束括号,但是当我在这里移动代码时它们就丢失了)

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 *)) { void *p1, *p2; void *last = base + (size*(nelem-1)); for (size_t curpos = nelem-1; curpos>0; curpos-2){ p1 = base + ((curpos-1)/2)*size; if(compar(last, (last-size)) >= 0){ if(compar(last, p1) > 0){ swap(last, p1, size); heapify(base, nelem, curpos, size, compar); } } else { //LEFT>RIGHT if(compar(last-size, p1) > 0){ swap(last-size, p1, size); heapify(base, 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 = base + (size*(nelem-1)); swap(base, last, size); nelem=nelem-1; heapify(base, 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 =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 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; } } } 

另外我有一个包含比较function的主文件。 本质上,数组的基址,元素数,每个元素的大小和比较函数都传递给我的heapsort函数。

当我运行程序时,我遇到了分段错误,我认为这意味着我正在尝试访问未分配给我的内存。 所以我想我想知道有没有人看到我访问非法内存地址的任何问题,或者可以指向我可以用来解决它的调试器?

谢谢!

调试器通常用于诊断内存错误源。 让我们知道从调试器运行代码时会发生什么。

 for (size_t curpos = nelem-1; curpos>0; curpos-2){ 

curpos-2没有任何影响。 你的意思是---=2

另外,严格地说,你不能对void *指针进行指针运算,即使你的编译器允许它,也不要依赖它。 相反,将它转换为char *以便保证ptr + x只会添加x个字节而不是x某个倍数。

您可能还会发现创建一个宏来索引元素数组很有用。 这将使您的代码更具可读性:

 #define ELEM(base, i) ((char *)(base) + (i)*size) 

您可以使用gdb来帮助调试它。 首先,使用-g编译程序以启用调试符号。 然后运行: gdb heapsort ,其中heapsort是程序的名称。 然后键入run ,按Enter键,等待它崩溃。 有用的命令包括用于回溯的bt和用于在变量中打印值的p