Rastislav Szabo | a17aa70 | 2016-02-26 15:01:28 +0100 | [diff] [blame^] | 1 | #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 | |
| 12 | void *xmalloc(unsigned n) |
| 13 | { |
| 14 | void *p; |
| 15 | p = malloc(n); |
| 16 | if(p) return p; |
| 17 | fprintf(stderr, "insufficient memory\n"); |
| 18 | exit(1); |
| 19 | } |
| 20 | |
| 21 | int compare(const void *pa, const void *pb, const void *config) |
| 22 | { |
| 23 | if(*(int *)pa < *(int *)pb) return -1; |
| 24 | if(*(int *)pa > *(int *)pb) return 1; |
| 25 | return 0; |
| 26 | } |
| 27 | |
| 28 | int main() |
| 29 | { |
| 30 | int i, *ptr; |
| 31 | const void *val; |
| 32 | struct rbtree *rb; |
| 33 | |
| 34 | if ((rb=rbinit(compare, NULL))==NULL) |
| 35 | { |
| 36 | fprintf(stderr, "insufficient memory\n"); |
| 37 | exit(1); |
| 38 | } |
| 39 | |
| 40 | for (i = 200; i > 0; i--) |
| 41 | { |
| 42 | ptr = (int *)xmalloc(sizeof(int)); |
| 43 | *ptr = i; |
| 44 | val = rbsearch((void *)ptr, rb); |
| 45 | if(val == NULL) |
| 46 | { |
| 47 | fprintf(stderr, "insufficient memory\n"); |
| 48 | exit(1); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | for(val=rblookup(RB_LUFIRST, NULL, rb); val!=NULL; val=rblookup(RB_LUNEXT, val, rb)) |
| 53 | { |
| 54 | printf("%6d\n", *(int *)val); |
| 55 | } |
| 56 | |
| 57 | rbdestroy(rb); |
| 58 | |
| 59 | return 0; |
| 60 | } |