2 Generic C code for red-black trees.
3 Copyright (C) 2000 James S. Plank
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 /* Revision 1.2. Jim Plank */
25 /* an example -- this allocates a red-black tree for integers. For a
26 * user-specified number of iterations, it does the following:
28 * delete a random element in the tree.
29 * make two new random elements, and insert them into the tree
31 * At the end, it prints the sorted list of elements, and then prints
32 * stats of the number of black nodes in any path in the tree, and
33 * the minimum and maximum path lengths.
35 * Rb_find_ikey and rb_inserti could have been used, but instead
36 * rb_find_gkey and rb_insertg were used to show how they work.
40 int icomp(char *i
, char *j
)
47 if (I
> J
) return -1; else return 1;
50 main(int argc
, char **argv
)
52 int i
, j
, tb
, nb
, mxp
, mnp
, p
;
58 fprintf(stderr
, "usage: main #iterations\n");
63 iterations
= atoi(argv
[1]);
64 a
= (int *) malloc (iterations
*sizeof(int));
66 for (i
= 0; i
< atoi(argv
[1]); i
++) {
70 rb_delete_node(rb_find_gkey(argt
, (char *) (a
[j
]), icomp
));
71 a
[j
] = random() % 1000;
72 rb_insertg(argt
, (char *) (a
[j
]), NULL
, icomp
);
74 a
[i
] = random() % 1000;
75 rb_insertg(argt
, (char *) (a
[i
]), NULL
, icomp
);
80 rb_traverse(t
, argt
) {
81 printf("%d ", t
->k
.ikey
);
86 } else if (tb
!= nb
) {
87 printf("Conflict: tb=%d, nb=%d\n", tb
, nb
);
90 mxp
= (mxp
== 0 || mxp
< p
) ? p
: mxp
;
91 mnp
= (mnp
== 0 || mxp
> p
) ? p
: mnp
;
95 printf("Nblack = %d\n", tb
);
96 printf("Max = %d\n", mxp
);
97 printf("Min = %d\n", mnp
);