|
| 1 | +// This file contains code snippets from "Algorithms in C, Third Edition, |
| 2 | +// Parts 1-4," by Robert Sedgewick. |
| 3 | +// |
| 4 | +// See https://www.cs.princeton.edu/~rs/Algs3.c1-4/code.txt |
| 5 | + |
| 6 | +#include <stdlib.h> |
| 7 | +#include <assert.h> |
| 8 | + |
| 9 | +#define N 1000 |
| 10 | + |
| 11 | + |
| 12 | +#ifdef ENABLE_KLEE |
| 13 | +#include <klee/klee.h> |
| 14 | +#endif |
| 15 | + |
| 16 | +typedef int Key; |
| 17 | +typedef int Item; |
| 18 | + |
| 19 | +#define eq(A, B) (!less(A, B) && !less(B, A)) |
| 20 | +#define key(A) (A) |
| 21 | +#define less(A, B) (key(A) < key(B)) |
| 22 | +#define NULLitem 0 |
| 23 | + |
| 24 | +struct STnode; |
| 25 | +typedef struct STnode* link; |
| 26 | + |
| 27 | +struct STnode { Item item; link l, r; int n; }; |
| 28 | +static link head, z; |
| 29 | + |
| 30 | +static link NEW(Item item, link l, link r, int n) { |
| 31 | + link x = malloc(sizeof *x); |
| 32 | + x->item = item; x->l = l; x->r = r; x->n = n; |
| 33 | + return x; |
| 34 | +} |
| 35 | + |
| 36 | +void STinit() { |
| 37 | + head = (z = NEW(NULLitem, 0, 0, 0)); |
| 38 | +} |
| 39 | + |
| 40 | +int STcount() { return head->n; } |
| 41 | + |
| 42 | +static link insertR(link h, Item item) { |
| 43 | + Key v = key(item), t = key(h->item); |
| 44 | + if (h == z) return NEW(item, z, z, 1); |
| 45 | + |
| 46 | + if (less(v, t)) |
| 47 | + h->l = insertR(h->l, item); |
| 48 | + else |
| 49 | + h->r = insertR(h->r, item); |
| 50 | + |
| 51 | + (h->n)++; return h; |
| 52 | +} |
| 53 | + |
| 54 | +void STinsert(Item item) { head = insertR(head, item); } |
| 55 | + |
| 56 | +static void sortR(link h, void (*visit)(Item)) { |
| 57 | + if (h == z) return; |
| 58 | + sortR(h->l, visit); |
| 59 | + visit(h->item); |
| 60 | + sortR(h->r, visit); |
| 61 | +} |
| 62 | + |
| 63 | +void STsort(void (*visit)(Item)) { sortR(head, visit); } |
| 64 | + |
| 65 | + |
| 66 | +static Item a[N]; |
| 67 | +static unsigned k = 0; |
| 68 | +void sorter(Item item) { |
| 69 | + a[k++] = item; |
| 70 | +} |
| 71 | + |
| 72 | +#ifdef ENABLE_CPROVER |
| 73 | +int nondet_int(); |
| 74 | +#endif |
| 75 | + |
| 76 | +// Unwind N+1 times |
| 77 | +int main() { |
| 78 | +#ifdef ENABLE_KLEE |
| 79 | + klee_make_symbolic(a, sizeof(a), "a"); |
| 80 | +#endif |
| 81 | + |
| 82 | + STinit(); |
| 83 | + |
| 84 | + for (unsigned i = 0; i < N; i++) { |
| 85 | +#ifdef ENABLE_CPROVER |
| 86 | + STinsert(nondet_int()); |
| 87 | +#elif ENABLE_KLEE |
| 88 | + STinsert(a[i]); |
| 89 | + a[i] = NULLitem; |
| 90 | +#endif |
| 91 | + } |
| 92 | + |
| 93 | + STsort(sorter); |
| 94 | + |
| 95 | +#ifndef FORCE_BRANCH |
| 96 | + for (unsigned i = 0; i < N - 1; i++) |
| 97 | + assert(a[i] <= a[i+1]); |
| 98 | +#endif |
| 99 | + |
| 100 | + return 0; |
| 101 | +} |
0 commit comments