-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnbest.h
73 lines (67 loc) · 1.73 KB
/
nbest.h
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
/*--------------------------------------------------------------*
* Definitions for a heap to keep the 'n' best items from
* a sequence presented.
* Includer must define:
* NBMAX Number of items to store
* NBTYPE Type of items
* NBBETTER(x,y) Comparison of two NBTYPE pointers
*--------------------------------------------------------------*/
static NBTYPE nb_item[NBMAX];
static NBTYPE *nb_ptr[NBMAX];
static NBTYPE *nb_sorted[NBMAX];
static int nb_count = 0;
static void nbshuffle(NBTYPE *ptr[], int n)
{
int i, j;
for (i=0;;) {
if ((j=2*i+2) < n && NBBETTER(ptr[2*i+1],ptr[j])) {
if (NBBETTER(ptr[i],ptr[j])) {
NBTYPE *temp = ptr[i]; /* swap with right child */
ptr[i] = ptr[j];
ptr[j] = temp;
}
i = j;
}else if ((j=2*i+1) < n) {
if (NBBETTER(ptr[i],ptr[j])) {
NBTYPE *temp = ptr[i]; /* swap with right child */
ptr[i] = ptr[j];
ptr[j] = temp;
}
i = j;
}else{
break;
}
}
}
static void nb_add(NBTYPE *value)
{
int i, j;
if (nb_count < NBMAX) {
i = nb_count++;
nb_item[i] = *value; /* save value */
nb_ptr[i] = &nb_item[i];
while (i > 0 && (j = (i-1)/2, NBBETTER(nb_ptr[j],nb_ptr[i]))) {
NBTYPE *temp = nb_ptr[i];
nb_ptr[i] = nb_ptr[j];
nb_ptr[j] = temp;
i = j;
}
}else if (NBBETTER(value,nb_ptr[0])) { /* better than least good */
*nb_ptr[0] = *value; /* replace value */
nbshuffle(nb_ptr, nb_count);
}
}
static void nb_sort(void)
{
NBTYPE *temp;
int i;
for (i=0; i<nb_count; i++) {
nb_sorted[i] = nb_ptr[i];
}
for (i=nb_count; i>0; ) {
temp = nb_sorted[0];
nb_sorted[0] = nb_sorted[--i];
nbshuffle(nb_sorted, i);
nb_sorted[i] = temp;
}
}