PageRenderTime 46ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/util-linux-2.21.2/floppy-0.18/intl/tsearch.c

#
C | 684 lines | 411 code | 75 blank | 198 comment | 123 complexity | c57bf514d25f8c799babb867581d0ac1 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, GPL-3.0
  1. /* Copyright (C) 1995, 1996, 1997, 2000, 2006 Free Software Foundation, Inc.
  2. Contributed by Bernd Schmidt <crux@Pool.Informatik.RWTH-Aachen.DE>, 1997.
  3. NOTE: The canonical source of this file is maintained with the GNU C
  4. Library. Bugs can be reported to bug-glibc@gnu.org.
  5. This program is free software; you can redistribute it and/or modify it
  6. under the terms of the GNU Library General Public License as published
  7. by the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Library General Public License for more details.
  13. You should have received a copy of the GNU Library General Public
  14. License along with this program; if not, write to the Free Software
  15. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
  16. USA. */
  17. /* Tree search for red/black trees.
  18. The algorithm for adding nodes is taken from one of the many "Algorithms"
  19. books by Robert Sedgewick, although the implementation differs.
  20. The algorithm for deleting nodes can probably be found in a book named
  21. "Introduction to Algorithms" by Cormen/Leiserson/Rivest. At least that's
  22. the book that my professor took most algorithms from during the "Data
  23. Structures" course...
  24. Totally public domain. */
  25. /* Red/black trees are binary trees in which the edges are colored either red
  26. or black. They have the following properties:
  27. 1. The number of black edges on every path from the root to a leaf is
  28. constant.
  29. 2. No two red edges are adjacent.
  30. Therefore there is an upper bound on the length of every path, it's
  31. O(log n) where n is the number of nodes in the tree. No path can be longer
  32. than 1+2*P where P is the length of the shortest path in the tree.
  33. Useful for the implementation:
  34. 3. If one of the children of a node is NULL, then the other one is red
  35. (if it exists).
  36. In the implementation, not the edges are colored, but the nodes. The color
  37. interpreted as the color of the edge leading to this node. The color is
  38. meaningless for the root node, but we color the root node black for
  39. convenience. All added nodes are red initially.
  40. Adding to a red/black tree is rather easy. The right place is searched
  41. with a usual binary tree search. Additionally, whenever a node N is
  42. reached that has two red successors, the successors are colored black and
  43. the node itself colored red. This moves red edges up the tree where they
  44. pose less of a problem once we get to really insert the new node. Changing
  45. N's color to red may violate rule 2, however, so rotations may become
  46. necessary to restore the invariants. Adding a new red leaf may violate
  47. the same rule, so afterwards an additional check is run and the tree
  48. possibly rotated.
  49. Deleting is hairy. There are mainly two nodes involved: the node to be
  50. deleted (n1), and another node that is to be unchained from the tree (n2).
  51. If n1 has a successor (the node with a smallest key that is larger than
  52. n1), then the successor becomes n2 and its contents are copied into n1,
  53. otherwise n1 becomes n2.
  54. Unchaining a node may violate rule 1: if n2 is black, one subtree is
  55. missing one black edge afterwards. The algorithm must try to move this
  56. error upwards towards the root, so that the subtree that does not have
  57. enough black edges becomes the whole tree. Once that happens, the error
  58. has disappeared. It may not be necessary to go all the way up, since it
  59. is possible that rotations and recoloring can fix the error before that.
  60. Although the deletion algorithm must walk upwards through the tree, we
  61. do not store parent pointers in the nodes. Instead, delete allocates a
  62. small array of parent pointers and fills it while descending the tree.
  63. Since we know that the length of a path is O(log n), where n is the number
  64. of nodes, this is likely to use less memory. */
  65. /* Tree rotations look like this:
  66. A C
  67. / \ / \
  68. B C A G
  69. / \ / \ --> / \
  70. D E F G B F
  71. / \
  72. D E
  73. In this case, A has been rotated left. This preserves the ordering of the
  74. binary tree. */
  75. #include <config.h>
  76. /* Specification. */
  77. #ifdef IN_LIBINTL
  78. # include "tsearch.h"
  79. #else
  80. # include <search.h>
  81. #endif
  82. #include <stdlib.h>
  83. typedef int (*__compar_fn_t) (const void *, const void *);
  84. typedef void (*__action_fn_t) (const void *, VISIT, int);
  85. #ifndef weak_alias
  86. # define __tsearch tsearch
  87. # define __tfind tfind
  88. # define __tdelete tdelete
  89. # define __twalk twalk
  90. #endif
  91. #ifndef internal_function
  92. /* Inside GNU libc we mark some function in a special way. In other
  93. environments simply ignore the marking. */
  94. # define internal_function
  95. #endif
  96. typedef struct node_t
  97. {
  98. /* Callers expect this to be the first element in the structure - do not
  99. move! */
  100. const void *key;
  101. struct node_t *left;
  102. struct node_t *right;
  103. unsigned int red:1;
  104. } *node;
  105. typedef const struct node_t *const_node;
  106. #undef DEBUGGING
  107. #ifdef DEBUGGING
  108. /* Routines to check tree invariants. */
  109. #include <assert.h>
  110. #define CHECK_TREE(a) check_tree(a)
  111. static void
  112. check_tree_recurse (node p, int d_sofar, int d_total)
  113. {
  114. if (p == NULL)
  115. {
  116. assert (d_sofar == d_total);
  117. return;
  118. }
  119. check_tree_recurse (p->left, d_sofar + (p->left && !p->left->red), d_total);
  120. check_tree_recurse (p->right, d_sofar + (p->right && !p->right->red), d_total);
  121. if (p->left)
  122. assert (!(p->left->red && p->red));
  123. if (p->right)
  124. assert (!(p->right->red && p->red));
  125. }
  126. static void
  127. check_tree (node root)
  128. {
  129. int cnt = 0;
  130. node p;
  131. if (root == NULL)
  132. return;
  133. root->red = 0;
  134. for(p = root->left; p; p = p->left)
  135. cnt += !p->red;
  136. check_tree_recurse (root, 0, cnt);
  137. }
  138. #else
  139. #define CHECK_TREE(a)
  140. #endif
  141. /* Possibly "split" a node with two red successors, and/or fix up two red
  142. edges in a row. ROOTP is a pointer to the lowest node we visited, PARENTP
  143. and GPARENTP pointers to its parent/grandparent. P_R and GP_R contain the
  144. comparison values that determined which way was taken in the tree to reach
  145. ROOTP. MODE is 1 if we need not do the split, but must check for two red
  146. edges between GPARENTP and ROOTP. */
  147. static void
  148. maybe_split_for_insert (node *rootp, node *parentp, node *gparentp,
  149. int p_r, int gp_r, int mode)
  150. {
  151. node root = *rootp;
  152. node *rp, *lp;
  153. rp = &(*rootp)->right;
  154. lp = &(*rootp)->left;
  155. /* See if we have to split this node (both successors red). */
  156. if (mode == 1
  157. || ((*rp) != NULL && (*lp) != NULL && (*rp)->red && (*lp)->red))
  158. {
  159. /* This node becomes red, its successors black. */
  160. root->red = 1;
  161. if (*rp)
  162. (*rp)->red = 0;
  163. if (*lp)
  164. (*lp)->red = 0;
  165. /* If the parent of this node is also red, we have to do
  166. rotations. */
  167. if (parentp != NULL && (*parentp)->red)
  168. {
  169. node gp = *gparentp;
  170. node p = *parentp;
  171. /* There are two main cases:
  172. 1. The edge types (left or right) of the two red edges differ.
  173. 2. Both red edges are of the same type.
  174. There exist two symmetries of each case, so there is a total of
  175. 4 cases. */
  176. if ((p_r > 0) != (gp_r > 0))
  177. {
  178. /* Put the child at the top of the tree, with its parent
  179. and grandparent as successors. */
  180. p->red = 1;
  181. gp->red = 1;
  182. root->red = 0;
  183. if (p_r < 0)
  184. {
  185. /* Child is left of parent. */
  186. p->left = *rp;
  187. *rp = p;
  188. gp->right = *lp;
  189. *lp = gp;
  190. }
  191. else
  192. {
  193. /* Child is right of parent. */
  194. p->right = *lp;
  195. *lp = p;
  196. gp->left = *rp;
  197. *rp = gp;
  198. }
  199. *gparentp = root;
  200. }
  201. else
  202. {
  203. *gparentp = *parentp;
  204. /* Parent becomes the top of the tree, grandparent and
  205. child are its successors. */
  206. p->red = 0;
  207. gp->red = 1;
  208. if (p_r < 0)
  209. {
  210. /* Left edges. */
  211. gp->left = p->right;
  212. p->right = gp;
  213. }
  214. else
  215. {
  216. /* Right edges. */
  217. gp->right = p->left;
  218. p->left = gp;
  219. }
  220. }
  221. }
  222. }
  223. }
  224. /* Find or insert datum into search tree.
  225. KEY is the key to be located, ROOTP is the address of tree root,
  226. COMPAR the ordering function. */
  227. void *
  228. __tsearch (const void *key, void **vrootp, __compar_fn_t compar)
  229. {
  230. node q;
  231. node *parentp = NULL, *gparentp = NULL;
  232. node *rootp = (node *) vrootp;
  233. node *nextp;
  234. int r = 0, p_r = 0, gp_r = 0; /* No they might not, Mr Compiler. */
  235. if (rootp == NULL)
  236. return NULL;
  237. /* This saves some additional tests below. */
  238. if (*rootp != NULL)
  239. (*rootp)->red = 0;
  240. CHECK_TREE (*rootp);
  241. nextp = rootp;
  242. while (*nextp != NULL)
  243. {
  244. node root = *rootp;
  245. r = (*compar) (key, root->key);
  246. if (r == 0)
  247. return root;
  248. maybe_split_for_insert (rootp, parentp, gparentp, p_r, gp_r, 0);
  249. /* If that did any rotations, parentp and gparentp are now garbage.
  250. That doesn't matter, because the values they contain are never
  251. used again in that case. */
  252. nextp = r < 0 ? &root->left : &root->right;
  253. if (*nextp == NULL)
  254. break;
  255. gparentp = parentp;
  256. parentp = rootp;
  257. rootp = nextp;
  258. gp_r = p_r;
  259. p_r = r;
  260. }
  261. q = (struct node_t *) malloc (sizeof (struct node_t));
  262. if (q != NULL)
  263. {
  264. *nextp = q; /* link new node to old */
  265. q->key = key; /* initialize new node */
  266. q->red = 1;
  267. q->left = q->right = NULL;
  268. if (nextp != rootp)
  269. /* There may be two red edges in a row now, which we must avoid by
  270. rotating the tree. */
  271. maybe_split_for_insert (nextp, rootp, parentp, r, p_r, 1);
  272. }
  273. return q;
  274. }
  275. #ifdef weak_alias
  276. weak_alias (__tsearch, tsearch)
  277. #endif
  278. /* Find datum in search tree.
  279. KEY is the key to be located, ROOTP is the address of tree root,
  280. COMPAR the ordering function. */
  281. void *
  282. __tfind (key, vrootp, compar)
  283. const void *key;
  284. void *const *vrootp;
  285. __compar_fn_t compar;
  286. {
  287. node *rootp = (node *) vrootp;
  288. if (rootp == NULL)
  289. return NULL;
  290. CHECK_TREE (*rootp);
  291. while (*rootp != NULL)
  292. {
  293. node root = *rootp;
  294. int r;
  295. r = (*compar) (key, root->key);
  296. if (r == 0)
  297. return root;
  298. rootp = r < 0 ? &root->left : &root->right;
  299. }
  300. return NULL;
  301. }
  302. #ifdef weak_alias
  303. weak_alias (__tfind, tfind)
  304. #endif
  305. /* Delete node with given key.
  306. KEY is the key to be deleted, ROOTP is the address of the root of tree,
  307. COMPAR the comparison function. */
  308. void *
  309. __tdelete (const void *key, void **vrootp, __compar_fn_t compar)
  310. {
  311. node p, q, r, retval;
  312. int cmp;
  313. node *rootp = (node *) vrootp;
  314. node root, unchained;
  315. /* Stack of nodes so we remember the parents without recursion. It's
  316. _very_ unlikely that there are paths longer than 40 nodes. The tree
  317. would need to have around 250.000 nodes. */
  318. int stacksize = 100;
  319. int sp = 0;
  320. node *nodestack[100];
  321. if (rootp == NULL)
  322. return NULL;
  323. p = *rootp;
  324. if (p == NULL)
  325. return NULL;
  326. CHECK_TREE (p);
  327. while ((cmp = (*compar) (key, (*rootp)->key)) != 0)
  328. {
  329. if (sp == stacksize)
  330. abort ();
  331. nodestack[sp++] = rootp;
  332. p = *rootp;
  333. rootp = ((cmp < 0)
  334. ? &(*rootp)->left
  335. : &(*rootp)->right);
  336. if (*rootp == NULL)
  337. return NULL;
  338. }
  339. /* This is bogus if the node to be deleted is the root... this routine
  340. really should return an integer with 0 for success, -1 for failure
  341. and errno = ESRCH or something. */
  342. retval = p;
  343. /* We don't unchain the node we want to delete. Instead, we overwrite
  344. it with its successor and unchain the successor. If there is no
  345. successor, we really unchain the node to be deleted. */
  346. root = *rootp;
  347. r = root->right;
  348. q = root->left;
  349. if (q == NULL || r == NULL)
  350. unchained = root;
  351. else
  352. {
  353. node *parent = rootp, *up = &root->right;
  354. for (;;)
  355. {
  356. if (sp == stacksize)
  357. abort ();
  358. nodestack[sp++] = parent;
  359. parent = up;
  360. if ((*up)->left == NULL)
  361. break;
  362. up = &(*up)->left;
  363. }
  364. unchained = *up;
  365. }
  366. /* We know that either the left or right successor of UNCHAINED is NULL.
  367. R becomes the other one, it is chained into the parent of UNCHAINED. */
  368. r = unchained->left;
  369. if (r == NULL)
  370. r = unchained->right;
  371. if (sp == 0)
  372. *rootp = r;
  373. else
  374. {
  375. q = *nodestack[sp-1];
  376. if (unchained == q->right)
  377. q->right = r;
  378. else
  379. q->left = r;
  380. }
  381. if (unchained != root)
  382. root->key = unchained->key;
  383. if (!unchained->red)
  384. {
  385. /* Now we lost a black edge, which means that the number of black
  386. edges on every path is no longer constant. We must balance the
  387. tree. */
  388. /* NODESTACK now contains all parents of R. R is likely to be NULL
  389. in the first iteration. */
  390. /* NULL nodes are considered black throughout - this is necessary for
  391. correctness. */
  392. while (sp > 0 && (r == NULL || !r->red))
  393. {
  394. node *pp = nodestack[sp - 1];
  395. p = *pp;
  396. /* Two symmetric cases. */
  397. if (r == p->left)
  398. {
  399. /* Q is R's brother, P is R's parent. The subtree with root
  400. R has one black edge less than the subtree with root Q. */
  401. q = p->right;
  402. if (q->red)
  403. {
  404. /* If Q is red, we know that P is black. We rotate P left
  405. so that Q becomes the top node in the tree, with P below
  406. it. P is colored red, Q is colored black.
  407. This action does not change the black edge count for any
  408. leaf in the tree, but we will be able to recognize one
  409. of the following situations, which all require that Q
  410. is black. */
  411. q->red = 0;
  412. p->red = 1;
  413. /* Left rotate p. */
  414. p->right = q->left;
  415. q->left = p;
  416. *pp = q;
  417. /* Make sure pp is right if the case below tries to use
  418. it. */
  419. nodestack[sp++] = pp = &q->left;
  420. q = p->right;
  421. }
  422. /* We know that Q can't be NULL here. We also know that Q is
  423. black. */
  424. if ((q->left == NULL || !q->left->red)
  425. && (q->right == NULL || !q->right->red))
  426. {
  427. /* Q has two black successors. We can simply color Q red.
  428. The whole subtree with root P is now missing one black
  429. edge. Note that this action can temporarily make the
  430. tree invalid (if P is red). But we will exit the loop
  431. in that case and set P black, which both makes the tree
  432. valid and also makes the black edge count come out
  433. right. If P is black, we are at least one step closer
  434. to the root and we'll try again the next iteration. */
  435. q->red = 1;
  436. r = p;
  437. }
  438. else
  439. {
  440. /* Q is black, one of Q's successors is red. We can
  441. repair the tree with one operation and will exit the
  442. loop afterwards. */
  443. if (q->right == NULL || !q->right->red)
  444. {
  445. /* The left one is red. We perform the same action as
  446. in maybe_split_for_insert where two red edges are
  447. adjacent but point in different directions:
  448. Q's left successor (let's call it Q2) becomes the
  449. top of the subtree we are looking at, its parent (Q)
  450. and grandparent (P) become its successors. The former
  451. successors of Q2 are placed below P and Q.
  452. P becomes black, and Q2 gets the color that P had.
  453. This changes the black edge count only for node R and
  454. its successors. */
  455. node q2 = q->left;
  456. q2->red = p->red;
  457. p->right = q2->left;
  458. q->left = q2->right;
  459. q2->right = q;
  460. q2->left = p;
  461. *pp = q2;
  462. p->red = 0;
  463. }
  464. else
  465. {
  466. /* It's the right one. Rotate P left. P becomes black,
  467. and Q gets the color that P had. Q's right successor
  468. also becomes black. This changes the black edge
  469. count only for node R and its successors. */
  470. q->red = p->red;
  471. p->red = 0;
  472. q->right->red = 0;
  473. /* left rotate p */
  474. p->right = q->left;
  475. q->left = p;
  476. *pp = q;
  477. }
  478. /* We're done. */
  479. sp = 1;
  480. r = NULL;
  481. }
  482. }
  483. else
  484. {
  485. /* Comments: see above. */
  486. q = p->left;
  487. if (q->red)
  488. {
  489. q->red = 0;
  490. p->red = 1;
  491. p->left = q->right;
  492. q->right = p;
  493. *pp = q;
  494. nodestack[sp++] = pp = &q->right;
  495. q = p->left;
  496. }
  497. if ((q->right == NULL || !q->right->red)
  498. && (q->left == NULL || !q->left->red))
  499. {
  500. q->red = 1;
  501. r = p;
  502. }
  503. else
  504. {
  505. if (q->left == NULL || !q->left->red)
  506. {
  507. node q2 = q->right;
  508. q2->red = p->red;
  509. p->left = q2->right;
  510. q->right = q2->left;
  511. q2->left = q;
  512. q2->right = p;
  513. *pp = q2;
  514. p->red = 0;
  515. }
  516. else
  517. {
  518. q->red = p->red;
  519. p->red = 0;
  520. q->left->red = 0;
  521. p->left = q->right;
  522. q->right = p;
  523. *pp = q;
  524. }
  525. sp = 1;
  526. r = NULL;
  527. }
  528. }
  529. --sp;
  530. }
  531. if (r != NULL)
  532. r->red = 0;
  533. }
  534. free (unchained);
  535. return retval;
  536. }
  537. #ifdef weak_alias
  538. weak_alias (__tdelete, tdelete)
  539. #endif
  540. /* Walk the nodes of a tree.
  541. ROOT is the root of the tree to be walked, ACTION the function to be
  542. called at each node. LEVEL is the level of ROOT in the whole tree. */
  543. static void
  544. internal_function
  545. trecurse (const void *vroot, __action_fn_t action, int level)
  546. {
  547. const_node root = (const_node) vroot;
  548. if (root->left == NULL && root->right == NULL)
  549. (*action) (root, leaf, level);
  550. else
  551. {
  552. (*action) (root, preorder, level);
  553. if (root->left != NULL)
  554. trecurse (root->left, action, level + 1);
  555. (*action) (root, postorder, level);
  556. if (root->right != NULL)
  557. trecurse (root->right, action, level + 1);
  558. (*action) (root, endorder, level);
  559. }
  560. }
  561. /* Walk the nodes of a tree.
  562. ROOT is the root of the tree to be walked, ACTION the function to be
  563. called at each node. */
  564. void
  565. __twalk (const void *vroot, __action_fn_t action)
  566. {
  567. const_node root = (const_node) vroot;
  568. CHECK_TREE (root);
  569. if (root != NULL && action != NULL)
  570. trecurse (root, action, 0);
  571. }
  572. #ifdef weak_alias
  573. weak_alias (__twalk, twalk)
  574. #endif
  575. #ifdef _LIBC
  576. /* The standardized functions miss an important functionality: the
  577. tree cannot be removed easily. We provide a function to do this. */
  578. static void
  579. internal_function
  580. tdestroy_recurse (node root, __free_fn_t freefct)
  581. {
  582. if (root->left != NULL)
  583. tdestroy_recurse (root->left, freefct);
  584. if (root->right != NULL)
  585. tdestroy_recurse (root->right, freefct);
  586. (*freefct) ((void *) root->key);
  587. /* Free the node itself. */
  588. free (root);
  589. }
  590. void
  591. __tdestroy (void *vroot, __free_fn_t freefct)
  592. {
  593. node root = (node) vroot;
  594. CHECK_TREE (root);
  595. if (root != NULL)
  596. tdestroy_recurse (root, freefct);
  597. }
  598. weak_alias (__tdestroy, tdestroy)
  599. #endif /* _LIBC */