Introduction to Computer Science - Fall 2004

/* Author:Yana
Module: binsearch.c

What:
-----
Searching a number in SORTED array
and returning its location if found.
Input: N integers separated by a space from
each other, followed by the number
to search.
Output: The location of the number, if found
or an appropriate message otherwise.
Assumption on input: valid.

How
-----
Algorithm: binary search
*/

#include < stdio.h >
#defne SIZE 10 /* size of input */

/* function prototypes */
int BinarySearch (int A[], int low, int high, int val) ;

int main (){

    int array[SIZE]; /* array for input */
    int i; /* index in the array */
    int number; /* A number to search */
    int location; /* Location of number in list, if exists, -1 if doesn't exist */

    /* read input */
    printf("Please enter %d integers \n" , SIZE);
    for (i = 0; i < SIZE; i++){
      scanf("%d", &array[i] );
    }

    printf("\nPlease enter a number to locate: ");
    scanf("%d", &number);

    /* locate number */
    location = BinarySearch(array, 0, SIZE - 1, number);
    if (location != -1 )
      printf("The value %d appears in place %d \n", number, location );
    else
      printf("The value %d is not in the given array\n ", number);

    return 0;
}

/* BinarySearch: Search a given number in an array of numbers.
Parameters: A - array to search
low - low limit
high - high limit
val - value to search
Returns: the index of the searched element in the array or -1 if the element is not in the array
Algorithm: BinarySearch */

int BinarySearch (int A[], int low, int high, int val){

    int middle;

    while (low <= high ) {
      middle = (low + high) /2;
      if (val == A [ middle ] ){
        return middle;
      }
      else if ( val < A [ middle ] )
        high = middle - 1;
      else
        low = middle + 1;
    }
    return -1;
}