Writing binary Lookup functions
Program:
#include <stdio.h>
intBinsearch (int x, int arr[], int Len)//binsearch binary, to divide
{
int Left = 0;
int Right = Len -1;
while (left <= right)
{
int mid = left + (right-left)/2;
if (arr[mid] < x)
{
left = mid + 1;
}
Else if (arr[mid] = = x)
{
return mid;
}
Else
{
right = Mid-1;
}
return -1;
}
}
int Main ()
{
int arr[] = {1, +, 5 , +,--------
int num = 0;
int sz = sizeof (arr)/ sizeof (Arr[0]);
printf ("Please enter a number:");
scanf ("%d", &num);
int ret = binsearch (num, arr, SZ);
if (ret = =-1)
{
printf ("not exist\n");
}
Else
{
printf ("Location of the number:%d\n", ret + 1);
}
return 0;
}
Result one:
Please enter a number:Bayi
Number of positions:8
Please press any key to continue ...
Result two:
Please enter a number:
Not exist
Please press any key to continue ...
This article is from the "Rock Owl" blog, please be sure to keep this source http://yaoyaolx.blog.51cto.com/10732111/1725712
C Language: Writing binary lookup functions