blob: 66a34920d009cd4c16b80e01bb6c87d2a264a177 [file] [log] [blame]
Rastislav Szaboa17aa702016-02-26 15:01:28 +01001#include <redblack.h>
2#include <stdlib.h>
3#include <stdio.h>
4
5/*
6 * This script demonstrates the worst case scenario - entering
7 * the data already in sequence. This program enters 200 numbers
8 * in reverse sequence (200 to 0) and then prints them out in
9 * the usual order. This would kill a regular tree algorithm.
10 *
11 * This is the same as example1 & example2, except that the
12 * output is done using rbopenlist, rbreadlist & rbcloselist.
13 */
14
15void *xmalloc(unsigned n)
16{
17 void *p;
18 p = malloc(n);
19 if(p) return p;
20 fprintf(stderr, "insufficient memory\n");
21 exit(1);
22}
23
24int compare(const void *pa, const void *pb, const void *config)
25{
26 if(*(int *)pa < *(int *)pb) return -1;
27 if(*(int *)pa > *(int *)pb) return 1;
28 return 0;
29}
30
31int main()
32{
33 int i, *ptr;
34 const void *val;
35 struct rbtree *rb;
36 RBLIST *rblist;
37
38 if ((rb=rbinit(compare, NULL))==NULL)
39 {
40 fprintf(stderr, "insufficient memory from rbinit()\n");
41 exit(1);
42 }
43
44 for (i = 200; i > 0; i--)
45 {
46 ptr = (int *)xmalloc(sizeof(int));
47 *ptr = i;
48 val = rbsearch((void *)ptr, rb);
49 if(val == NULL)
50 {
51 fprintf(stderr, "insufficient memory from rbsearch()\n");
52 exit(1);
53 }
54 }
55
56 if ((rblist=rbopenlist(rb))==NULL)
57 {
58 fprintf(stderr, "insufficient memory from rbopenlist()\n");
59 exit(1);
60 }
61
62 while((val=rbreadlist(rblist)))
63 {
64 printf("%6d\n", *(int *)val);
65 }
66
67 rbcloselist(rblist);
68
69 rbdestroy(rb);
70
71 return 0;
72}