Skip to content

Commit

Permalink
Lower branches in red-black tree again (#59)
Browse files Browse the repository at this point in the history
This commit is similar with the one applied in insert_node, an
indirect pointer can be used instead of checking left or right
child nodes.
  • Loading branch information
steven1lung committed Sep 27, 2022
1 parent ff46dad commit 09f4e65
Showing 1 changed file with 14 additions and 26 deletions.
40 changes: 14 additions & 26 deletions src/map.c
Original file line number Diff line number Diff line change
Expand Up @@ -580,38 +580,26 @@ void map_find(map_t obj, map_iter_t *it, void *key)
}

/* Basically a repeat of insert */
map_node_t *cur = obj->head;
map_node_t **indirect = &obj->head;

/* binary search */
while (1) {
int res = obj->comparator(key, cur->key);
if (res == 0) /* If the key matches, we hit the target */
while (*indirect) {
int res = obj->comparator(key, (*indirect)->key);
if (res == 0)
break;

if (res < 0) {
if (!cur->left) {
cur = NULL;
break;
}
cur = cur->left;
} else {
if (!cur->right) {
cur = NULL;
break;
}
cur = cur->right;
}
indirect = res < 0 ? &(*indirect)->left : &(*indirect)->right;
}

if (cur) {
it->node = cur;

/* Generate a "prev" as well */
map_iter_t tmp = *it;
map_prev(obj, &tmp);
it->prev = tmp.node;
} else
if (!*indirect) {
it->node = NULL;
return;
}
it->node = *indirect;

/* Generate a "prev" as well */
map_iter_t tmp = *it;
map_prev(obj, &tmp);
it->prev = tmp.node;
}

bool map_empty(map_t obj)
Expand Down

0 comments on commit 09f4e65

Please sign in to comment.