SURFEX v8.1
General documentation of Surfex
bbt.c
Go to the documentation of this file.
1 #include <stdlib.h>
2 
3 #include "bbt.h"
4 
5 typedef struct bbt_treap {
6  BBT_HEADER(bbt_treap);
7 } bbt;
8 
9 static int pseudo_random(void) {
10 static int x0=5341;
11 
12  x0 = (22611*x0 + 10) % 44071;
13  return x0;
14 }
15 
16 static bbt *rotate_right(bbt *t) {
17 bbt *temp;
18 
19  temp = t->left;
20  t->left = t->left->right;
21  temp->right = t;
22 
23  return temp;
24 }
25 
26 static bbt *rotate_left(bbt *t) {
27 bbt *temp;
28 
29  temp = t->right;
30  t->right = t->right->left;
31  temp->left = t;
32 
33  return temp;
34 }
35 
36 static bbt *delete_root(bbt *t) {
37 bbt *temp;
38 
39  if (t->left == NULL)
40  return t->right;
41 
42  if (t->right == NULL)
43  return t->left;
44 
45  if (t->left->priority > t->right->priority) {
46  temp = rotate_right(t);
47  temp->right = delete_root(t);
48 
49  } else {
50  temp = rotate_left(t);
51  temp->left = delete_root(t);
52  }
53 
54  return temp;
55 }
56 
57 static bbt *delete_treap(bbt *old, bbt *t, int (*compare)()) {
58 int c;
59 
60  if (t == NULL)
61  return NULL;
62 
63  c = compare(old, t);
64 
65  if (c == 0)
66  t = delete_root(t);
67 
68  else if (c < 0)
69  t->left = delete_treap(old, t->left, compare);
70 
71  else if (c > 0)
72  t->right = delete_treap(old, t->right, compare);
73 
74  return t;
75 }
76 
77 void bbt_delete_bbt(void *root, void *old, int (*compare)()) {
78 bbt **t;
79 
80  t = (bbt **) root;
81 
82  *t = delete_treap((bbt *) old, *t, compare);
83 }
84 
85 static bbt *insert(bbt *new, bbt *t, int (*compare)()) {
86 int c;
87 
88  if (t == NULL)
89  return new;
90 
91  c = (*compare)(new, t);
92 
93  if (c == 0)
94  return NULL;
95 
96  if (c < 0) {
97  t->left = insert(new, t->left, compare);
98  if (t->priority < t->left->priority)
99  t = rotate_right(t);
100 
101  } else {
102  t->right = insert(new, t->right, compare);
103  if (t->priority < t->right->priority)
104  t = rotate_left(t);
105  }
106 
107 
108  return t;
109 }
110 
111 void bbt_insert_bbt(void *root, void *new, int (*compare)()) {
112 bbt **r, *n;
113 
114  r = (bbt **) root;
115  n = (bbt *) new;
116 
117  n->priority = pseudo_random();
118  *r = insert(n, *r, compare);
119 }
120 
static bbt * rotate_right(bbt *t)
Definition: bbt.c:16
struct bbt_treap bbt
static bbt * delete_root(bbt *t)
Definition: bbt.c:36
static bbt * insert(bbt *new, bbt *t, int(*compare)())
Definition: bbt.c:85
static int pseudo_random(void)
Definition: bbt.c:9
static bbt * rotate_left(bbt *t)
Definition: bbt.c:26
ERROR in n
Definition: ecsort_shared.h:90
void bbt_delete_bbt(void *root, void *old, int(*compare)())
Definition: bbt.c:77
static bbt * delete_treap(bbt *old, bbt *t, int(*compare)())
Definition: bbt.c:57
void bbt_insert_bbt(void *root, void *new, int(*compare)())
Definition: bbt.c:111
subroutine t(CDPREF, CDSUFF, KCODPA, LDNIVA, PMULTI)
Definition: faicor.F90:567