Я пытаюсь получить общий хаппорт. Он отлично работает со строками, но по какой-то причине не с целыми типами. Полностью потеряно, почему это так. Я уверен, что функция сравнения верна. Последнее утверждение if в функции heapsort заключается в исправлении ошибки, которая иногда приводит к обратному изменению 0-го и 1-го индексов.Heapsort, работающий со строками, но не ints
#include "heapsort.h"
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <sys/types.h>
int heapsort(void *base, size_t nel, size_t width, int (*compar)(const void *, const void *))
{
int i;
int j;
printf("\n");
/*build heap*/
for (j = 1; j < nel; j++) {
i = j;
while (compar(base + i * width, base + (i-1)/2 * width) > 0) {
swap(base + i * width, base + (i-1)/2 * width);
i = (i-1)/2;-
}
}
/*sort*/
for (i = 1; i < nel; i++) {
swap(base , base + (nel - i) * width);
j = 0;
while (((2 * j + 1) < nel - i) && ((2 * j + 2) < nel - i)){
if (compar(base + (j * 2 + 2) * width, base + (j * 2 + 1) * width) > 0
&& compar(base + j * width, base + (j * 2 + 2) * width) < 0)
{
swap(base + j * width, base + (2 * j + 2) * width);
j = 2 * j + 2;
}
else if (compar(base + (j * 2 + 2) * width, base + (j * 2 + 1) * width) <= 0
&& compar(base + j * width, base + (j * 2 + 1) * width) < 0)
{
swap(base + j * width, base + (2 * j + 1) * width);
j = 2 * j + 1;
}
else
break;
}
}
if (compar(base + 0 * width, base + 1 * width) > 0) {
swap(base + 0 * width, base + 1 * width);
}
return 0;
}
void swap(void *a, void *b)
{
void *temp;
printf("swapping %d and %d\n", *(int*)a, *(int*)b);
temp = *(void**)a;
*(void**)a = *(void**)b;
*(void**)b = temp;
}
int intcmp(const void * a, const void * b)
{
return *(int*)a - *(int*)b;
}
Было бы полезно, если вы поделитесь кодом для функции 'comp', которую вы отправляете в случае' int' –
@AmnonShochot Я добавил функцию сравнения, intcmp внизу – Connor
Вы добавили код для ' intcmp', но в вашей функции heapsort вы вызываете 'compare' – thurizas