The for's I have trouble with are the one in buildHeap and buildMinHeap. Previously, those didn't trigger at all which is why I know the printing part should more or less work as it printed the nodes properly, if with the unsorted array.
Currently I assume I have an infinite loop in there as the program crashes after displaying some of the debug messages I put in. I ran out of ideas on what could be wrong. Any ideas?
#include <stdio.h>
#define ARRAY_SIZE 10
int parent(int i) {
return i/2;
}
int left(int i) {
return 2*i;
}
int right(int i) {
return 2*i+1;
}
void heapify(int A[], int i, int s) {
int m = i;
int temp;
int l = left(i);
int r = right(i);
if (l <= s && A[l] > A[m]) m = l;
if (r <= s && A[r] > A[m]) m = r;
if (i != m) {
temp = A[i];
A[i] = A[m];
A[m] = temp;
heapify(A, m, s);
}
printf("heapify done\n");
}
void buildHeap(int A[]) {
int i;
for (i = ARRAY_SIZE / 2; i > 0; i--) {
heapify(A, i, ARRAY_SIZE);
}
printf("buildHeap done\n");
}
// this still creates a normal heap, not a min heap afaik
void buildMinHeap(int A[]) {
int s = ARRAY_SIZE - 1;
int i;
int temp;
buildHeap(A);
for (i = ARRAY_SIZE; i > 1; i--) {
temp = A[i];
A[i] = A[1];
A[1] = temp;
s = s-1;
heapify(A, 1, s);
}
}
void printHeap(int A[]) {
int i;
printf("graph g {\n");
for (i = 0; i < ARRAY_SIZE; i++) {
printf("%d -- %d\n", parent(i), A[i]);
}
printf(" }\n");
//temp debug code
printf("[ ");
i = 0;
for (i = 0; i < ARRAY_SIZE; i++) {
printf("%d", A[i]);
if (i < ARRAY_SIZE - 1) printf(", ");
}
printf(" ]\n");
}
int main() {
int array[ARRAY_SIZE] = {4, 3, 2, 5, 6, 7, 8, 9, 12, 1};
buildMinHeap(array);
printHeap(array);
}
EDIT: Oh, also, I'm still a student so not that versed in C just yet. Just to give some context.