Rastislav Szabo | a17aa70 | 2016-02-26 15:01:28 +0100 | [diff] [blame] | 1 | #include <redblack.h> |
| 2 | #include <stdlib.h> |
| 3 | #include <unistd.h> |
| 4 | #include <stdio.h> |
| 5 | |
| 6 | /* |
| 7 | * This script demonstrates the basic sorting capabilities. |
| 8 | * 12 random numbers are entered into the tree and then printed |
| 9 | * out in order |
| 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 | srand(getpid()); |
| 35 | |
| 36 | if ((rb=rbinit(compare, NULL))==NULL) |
| 37 | { |
| 38 | fprintf(stderr, "insufficient memory\n"); |
| 39 | exit(1); |
| 40 | } |
| 41 | |
| 42 | for (i = 0; i < 12; i++) |
| 43 | { |
| 44 | ptr = (int *)xmalloc(sizeof(int)); |
| 45 | *ptr = rand()&0xff; |
| 46 | val = rbsearch((void *)ptr, rb); |
| 47 | if(val == NULL) |
| 48 | { |
| 49 | fprintf(stderr, "insufficient memory\n"); |
| 50 | exit(1); |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | for(val=rblookup(RB_LUFIRST, NULL, rb); val!=NULL; val=rblookup(RB_LUNEXT, val, rb)) |
| 55 | { |
| 56 | printf("%6d\n", *(int *)val); |
| 57 | } |
| 58 | |
| 59 | rbdestroy(rb); |
| 60 | |
| 61 | return 0; |
| 62 | } |