-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHeap.c
More file actions
114 lines (97 loc) · 2.42 KB
/
Copy pathHeap.c
File metadata and controls
114 lines (97 loc) · 2.42 KB
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
#include "Heap.h"
struct Distance{
double value;
Shapelet candidate;
TimeSerie instance;
};
struct Heap{
Distance *array;
int size;
};
Distance getHeapValue(Heap H, int index){
return H->array[index];
}
int leftSon(int index){
return index*2;
}
int rightSon(int index){
return index*2+1;
}
int father(int index){
return index/2;
}
Heap createHeap(int size){
Heap T = (struct Heap*)malloc(sizeof(*T));
T->array = malloc(sizeof(Distance)*size);
T->array[0] = NULL;
T->size = 1;
return T;
}
void destroyHeap(Heap T){
// the inner distances are freed somewhere else
free(T->array);
free(T);
}
void addToHeap(Heap T, Distance distance){
T->array[T->size] = distance;
reorganizeUp(T,T->size);
T->size++;
}
void deleteFromHeap(Heap T){
--T->size;
T->array[1] = T->array[T->size];
reorganizeDown(T, 1);
}
void reorganizeUp(Heap T, int s){
if(s > 1){
int p = father(s);
double distance1 = getDistanceValue(getHeapValue(T,p));
double distance2 = getDistanceValue(getHeapValue(T,s));
if(distance1 < distance2){
Distance tmp = T->array[p];
T->array[p] = T->array[s];
T->array[s] = tmp;
reorganizeUp(T, p);
}
}
}
void reorganizeDown(Heap T, int s){
if(s < T->size){
int o = leftSon(s);
int p = rightSon(s);
if(o < T->size){
if(p < T->size){
if(getDistanceValue(getHeapValue(T,p)) > getDistanceValue(getHeapValue(T,o))){
o=p;
}
}
if(getDistanceValue(getHeapValue(T,o)) > getDistanceValue(getHeapValue(T,s))){
Distance tmp = T->array[o];
T->array[o] = T->array[s];
T->array[s] = tmp;
reorganizeDown(T,o);
}
}
}
}
Distance createDistance(double value, TimeSerie instance, TimeSerie shapelet){
Distance result = malloc(sizeof(*result));
result->value = value;
result->instance = instance;
result->candidate = shapelet;
return result;
}
void destroyDistance(Distance d){
free(d->instance);
free(d->candidate);
free(d);
}
double getDistanceValue(Distance distance){
return distance->value;
}
int getDistanceLabel(Distance distance){
return getLabel(distance->candidate);
}
TimeSerie getDistanceInstance(Distance d){
return d->instance;
}