home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C by Discovery (4th Edition)
/
C_By_Discovery_4th_Edition.tar
/
C_By_Discovery_4th_Edition
/
_DISK_
/
ch6
/
binsrch.c
next >
Wrap
C/C++ Source or Header
|
2005-06-16
|
2KB
|
66 lines
/* binsrch.c
*
* Synopsis - The program initializes an array at the time of
* declaration and prompts the user to enter a value to
* find in the array. The function bin_search() looks
* for that value and the results of the search is
* displayed.
*
* Objective - To see one method of searching an array.
*/
/* Header files */
#include <stdio.h>
/* Constant Definitions */
#define ARRAY_SIZE 11
/* Function Prototypes */
int bin_search( int desired_element, int array[], int first, int last );
/* PRECONDITION: desired_element is the value to search for.
* array is the array to search, first is the
* index of the first element in the part of the
* array to search and last is the index of the last
* element in the part of the array to search.
* array must be sorted in increasing order.
* POSTCONDITION: If desired_element is in array, the function
* returns an index in array where desired_element
* was found. If desired_element is not in the array,
* the value -1 is returned.
*/
int main()
{
int intvar, index;
int intarray[ARRAY_SIZE] = {-21, 3, 13, 23, 37, 45, 57, 67, 77, 89, 92};
printf( "What number do you want to search for? " );
scanf ( "%d", &intvar );
index = bin_search( intvar, intarray, 0, 10 );
if ( index == -1 )
printf( "%d is not in the array.\n", intvar );
else
printf( "%d is in the %dth cell of the array.\n", intvar, index + 1 );
return 0;
}
/*******************************bin_search()********************/
int bin_search( int desired_element, int array[], int first, int last )
{
int mid;
if ( first <= last ) { /* Note 1 */
mid = (first + last)/2;
if ( array[mid] > desired_element )
/* Note 2 */
return(bin_search(desired_element,array, first,mid-1));
else if ( array[mid] < desired_element )
/* Note 2 */
return(bin_search(desired_element,array,mid+1,last));
else
return mid;
}
else
return -1; /* Note 1 */
}