Vote count:
0
Im learning heap sort by cormen. when Im trying to run heapsort on the array, thers a problem and the program crashes (segmentation fault). I tried to put some printf's in the heapsort function and printing the h->size and h->count values but they seem to changed in some way from 10 to 3 (!!!) without me touching them (try to print them before the loop in heap_sort and after).. I really dont understand what is the problem. please help me. using Eclipse on windows7. thanks!!
main.c:
#include <stdio.h>
#include "heap.h"
void print_array2(int *a, int n)
{
int *end = a + n;
while (a < end)
printf("%d ", *a++);
printf("\n");
}
int main(void)
{
int a[] =
{ 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 };
print_array2(a, 10);
heapsort(a, 10);
print_array2(a, 10);
return 0;
}
heap.c:
#include <stdlib.h>
#include <stdio.h>
#include "heap.h"
void heapify(heap *h, int i)
{
int largest, left = LEFT(i), right = RIGHT(i);
if (left < h->count && (*(h->a + left) > *(h->a + i)))
largest = left;
else
largest = i;
if (right < h->count && (*(h->a + right) > *(h->a + largest)))
largest = right;
if (largest != i)
{
swap(h->a + i, h->a + largest);
heapify(h, largest);
}
}
heap *build_heap(int *a, int size)
{
heap h = (heap
)
{ .size = size, .count = size, .a = a };
heap *ph = &h;
int i = size / 2;
while (i >= 0)
heapify(ph, i--);
return ph;
}
void heapsort(int *a, int size)
{
heap *h = build_heap(a, size);
int i;
for (i = h->size - 1; i >= 1; --i)
{
swap(h->a, h->a + i);
h->count--;
heapify(h, 0);
}
}
void print_heap(heap *h)
{
int *end = h->a + h->count, *arr = h->a;
while (arr < end)
printf("%d ", *arr++);
printf("\n");
}
void print_array(heap *h)
{
int *end = h->a + h->size, *arr = h->a;
while (arr < end)
printf("%d ", *arr++);
printf("\n");
}
static void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
heap.h:
#ifndef HEAP_H_
#define HEAP_H_
typedef struct
{
int size; //array size
int count; //heap size
int *a; //int array
} heap;
#define PARENT(x) ((x + 1) / 2)
#define LEFT(x) (2 * (x) + 1)
#define RIGHT(x) (2 * ( (x) + 1) )
void heapify(heap* h, int i);
heap *build_heap(int *a, int size);
void heapsort(int *a, int size);
void print_heap(heap *h);
void print_array(heap *h);
static void swap(int *a, int *b);
#endif /* HEAP_H_ */
asked 21 secs ago
Aucun commentaire:
Enregistrer un commentaire