/* Timing linear and binary search
 * 15-122 Principle of Imperative Computation, Spring 2011
 * Frank Pfenning
 */

#use <conio>
#use "rand.h0"
#use "rand.c0"

/*
 * Need to run this without the search
 * to understand the behavior of setting
 * up the test as compared to performing it
 *
 * Argument passing could improve that, but
 * we avoid this complication
 */

int abs (int n)
//@requires n > (1<<31); /* overflow: -INT_MIN = INT_MIN < 0 */
//@ensures \result >= 0;
{
  return n >= 0 ? n : -n;
}

int main () {
  int seed = 0xdeadbeef;
  rand_t gen = init_rand(seed);
  int exp = 15;
  int n = 1<<exp;
  int num_tests = 1000;
  int[] A = alloc_array(int, n);
  int i; int j; int x; int dx;

  print("Timing "); printint(num_tests);
  print(" times with 2^"); printint(exp);
  print(" elements\n");

  /* generated sorted array */
  A[0] = 0;
  for (i = 0; i < n-1; i++) {
    dx = abs(rand(gen) % (((1<<31)-1)/n));
    A[i+1] = A[i]+dx;
  }

  /* timing search */
  /* first, elements in the array */
  for (i = 0; i < num_tests; i++) {
    j = abs(rand(gen) % n);
    linsearch(A[j], A, n);
  }
  /* then random elements */
  for (i = 0; i < num_tests; i++) {
    x = rand(gen);
    linsearch(x, A, n);
  }

  return 0;
}
