Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include "Heap.h"
#include "Sort.h"
#include <string.h>
#define max(x,y) ( ( (x)>(y) ) ? (x) : (y) )
void test_Heapify();
void test_HeapPush();
int main(int argc, char **argv) {
printf("Test Heap: ");
SetRandomSeed(111);
test_Heapify();
test_HeapPush();
printf("OK\n");
exit(0);
} /* end main */
int compareLong (const void *a, const void *b) {
long diff = *((long*)a) - *((long*)b);
if(diff == 0)
return 0;
return (diff < 0) ? -1 : 1;
} /* end compareLong */
int compare2ndLong (const void *a, const void *b) {
long diff = ((long*)a)[1] - ((long*)b)[1];
if(diff == 0)
return 0;
return (diff < 0) ? -1 : 1;
} /* end compare2ndLong */
/**
* Test Heapify()
*/
void test_Heapify() {
long N = 100, i;
long *items = (long*)malloc(2*N*sizeof(long));
long *heapItems = (long*)malloc(2*N*sizeof(long));
long tmp[2];
if (items == NULL || heapItems == NULL) {
printf("Error\n");
exit(1);
}
for(i=0; i<N; ++i) {
items[2*i ] = i;
items[2*i+1] = Random1(0, 50);
}
memcpy(heapItems, items, 2*N*sizeof(long));
struct heap Heap;
HeapInit(&Heap, 2*sizeof(long), compare2ndLong);
Heapify(&Heap, heapItems, N);
qsort(items, N, 2*sizeof(long), compare2ndLong);
for(i=0; i<N; ++i) {
HeapPop(&Heap, tmp);
if(tmp[1] != items[2*N-(2*i)-1]) {
printf("Error\n");
}
}
if(Heap.numItems > 0) {
printf("Error\n");
exit(1);
}
HeapDestroy(&Heap);
free(items);
} /* end Heapify */
/**
* Test HeapPush()
*/
void test_HeapPush() {
struct heap Heap;
HeapInit(&Heap, sizeof(long), compareLong);
long tmp[1], tmp2[1], i, N = 100, max = -1;
long *items = (long*)malloc(N*sizeof(long));
if (items == NULL) {
printf("Error\n");
exit(1);
}
for(i=0; i<N; ++i) {
*tmp = items[i] = Random1(0,N);
max = max(max, *tmp);
HeapPush(&Heap, tmp);
if(!HeapPeek(&Heap, tmp2) || *tmp2 != max) {
printf("Error\n");
exit(1);
}
}
qsort(items, N, sizeof(long), compareLong);
for(i=0; i<N; ++i) {
HeapPop(&Heap, tmp);
if(*tmp != items[N-i-1]) {
printf("Error\n");
}
}
if(Heap.numItems > 0) {
printf("Error\n");
exit(1);
}
HeapDestroy(&Heap);
free(items);
} /* end HeapPush */