/* This program illustrates the difference 
between linear and binary search in an array */

#include <stdio.h>
#include <stdlib.h>

#define ARRAY_SIZE 8

main() {

  int ar[ ARRAY_SIZE ] = {1, 2, 3, 4, 23, 48, 67, 112};
  int target;
  int high, mid, low;
  int i;

  // LINEAR SEARCH
  printf("\n\nLinear Search\n\n");

  // Ask for a number until EOF
  while ( scanf( "%d", &target ) !=EOF ) {

  // Linear search algorithm:
  // go in index order
  // until element is found
  // or no more elements left

    for ( i=0; ( i < ARRAY_SIZE ) && ( ar[i] != target ); i++ );

    // Why did the loop finish?

    if ( i != ARRAY_SIZE )
      printf ( "Found %d at position %d in array.\n", target, i );
    else printf ( "There is no %d in array.\n", target ); 
  }

  // BINARY SEARCH
  printf("\n\nBinary Search\n\n");

  // Ask for a number until EOF
  while ( scanf("%d", &target )!=EOF ) {

  // Binary search algorithm: 
  // (works only in an ordered or sorted array)
  // Repeatedly checks if the element is in the lower
  // half, or the upper half of the array,
  // and restricts the array based on the answer

    for ( low = 0, high = ARRAY_SIZE, mid = ARRAY_SIZE / 2; (low < high - 1) && ( target != ar[mid] ); mid = low + (high - low)/2 )
      if ( target > ar[mid] ) low = mid;
      else high = mid;

    // Why did the loop finish?

    if ( low < high - 1 ) printf ( "Found %d at position %d in array.\n", target, mid );
    else printf ( "There is no %d in array.\n", target );
 }
}

