blob: 8eb024d4477cd76e2fcc252b717cb5437e9c81d4 [file] [log] [blame]
brians343bc112013-02-10 01:53:46 +00001#include "binheap.h"
2#include <stdlib.h>
3#include <stdio.h>
4
5#ifndef TESTING_ASSERT
6#define TESTING_ASSERT(...)
7#endif
8#define Error(x) TESTING_ASSERT(0, x)
9
10#define MinData (0)
11
12void Initialize( int Elements, PriorityQueue H )
13{
14 H->Capacity = Elements - 1;
15 H->Size = 0;
16 H->Elements[ 0 ] = MinData;
17}
18
19int Insert( ElementType X, PriorityQueue H )
20{
21 int i;
22
23 if( IsFull( H ) )
24 {
25 return -1;
26 }
27
28 for( i = ++H->Size; H->Elements[ i / 2 ] > X; i /= 2 )
29 H->Elements[ i ] = H->Elements[ i / 2 ];
30 H->Elements[ i ] = X;
31 return 0;
32}
33
34void Remove( ElementType X, PriorityQueue H )
35{
36 int i, Child, removed = 0;
37 ElementType LastElement;
38
39 for ( i = 1; i <= H->Size; ++i )
40 {
41 if( H->Elements[ i ] == X )
42 {
43 removed = i;
44 break;
45 }
46 }
47 if( removed == 0 )
48 {
49 fprintf(stderr, "could not find element %d to remove. not removing any\n", X);
50 return;
51 }
52
53 LastElement = H->Elements[ H->Size-- ];
54
55 for( i = removed; i * 2 <= H->Size; i = Child )
56 {
57 /* Find smaller child */
58 Child = i * 2;
59 if( Child != H->Size && H->Elements[ Child + 1 ]
60 < H->Elements[ Child ] )
61 Child++;
62
63 /* Percolate one level */
64 if( LastElement > H->Elements[ Child ] )
65 H->Elements[ i ] = H->Elements[ Child ];
66 else
67 break;
68 }
69 H->Elements[ i ] = LastElement;
70}
71
72ElementType DeleteMin( PriorityQueue H )
73{
74 int i, Child;
75 ElementType MinElement, LastElement;
76
77 if( IsEmpty( H ) )
78 {
79 Error( "Priority queue is empty" );
80 return H->Elements[ 0 ];
81 }
82 MinElement = H->Elements[ 1 ];
83 LastElement = H->Elements[ H->Size-- ];
84
85 for( i = 1; i * 2 <= H->Size; i = Child )
86 {
87 /* Find smaller child */
88 Child = i * 2;
89 if( Child != H->Size && H->Elements[ Child + 1 ]
90 < H->Elements[ Child ] )
91 Child++;
92
93 /* Percolate one level */
94 if( LastElement > H->Elements[ Child ] )
95 H->Elements[ i ] = H->Elements[ Child ];
96 else
97 break;
98 }
99 H->Elements[ i ] = LastElement;
100 return MinElement;
101}
102
103ElementType GetMin( PriorityQueue H )
104{
105 if( !IsEmpty( H ) )
106 return H->Elements[ 1 ];
107 Error( "Priority Queue is Empty" );
108 return H->Elements[ 0 ];
109}
110
111int IsEmpty( PriorityQueue H )
112{
113 return H->Size == 0;
114}
115
116int IsFull( PriorityQueue H )
117{
118 return H->Size == H->Capacity;
119}
120
121int GetSize( PriorityQueue H )
122{
123 return H->Size;
124}
125