Search the list Item for ItemSought using binary search.
#include <stdio.h>
#define ArrSize 10
#define searchFor 7
/*
-BinarySearch------------------------------------------------
Function to search the list Item for ItemSought using
binary search. If ItemSought is not found in the list,
(-1) is returned. Otherwise the Location of the item is
returned;
Local variables used are:
First : first item in (sub)list being searched
Last : last " " " " "
Middle : middle " " " " "
Accepts: Array Item and ItemSought in the list Item
Returns: If ItemSought is found: position of ItemSought
Otherwise: (-1)
-------------------------------------------------------------*/
int BinarySearch(int Item[], int n, int ItemSought)
{
int First, Last, Middle;
First = 0;
Last = n-1;
// While First less than or equal to Last and not Found do the following:
do
{
// If empty list to be searched or the item is not found, return 0.
if (First > Last) return -1;
// Otherwise continue with the following
Middle = (First + Last) / 2;
if (ItemSought < Item[Middle])
Last = Middle - 1;
else if (ItemSought > Item[Middle])
First = Middle + 1;
else
return Middle;
} while (1);
return(-1);
}
void main()
{
int res=-1 ;
int arrNum[]={1,2,3,4,5,6,7,8,9,10}; // the array
res = BinarySearch(arrNum,ArrSize,searchFor); // the search
if ( res != (-1) ) // the output
printf("%d foud at place %d \n",searchFor,res);
else
printf("%d NOT foud in the arr \n",searchFor);
}