#include <stdio.h>
int search(int[],int,int);
int main(int argc, int *argv[])
{
int a[16] = {3,5,7,8,10,20,30,40,55,67,87,90,100,111,134,140};
int i,search_value;
int key;
for (i = 0; i < 16; i++)
{
printf("%4d",a[i]);
}
printf("\nplease input search number:");
scanf("%d",&search_value);
key = search(a,16,search_value);
if (key != -1)
{
printf("search %d in %d number.\n",search_value,key);
}
else
{
printf("not search %d.\n",search_value);
}
system("pause");
return 0;
}
int search(int arr[], int n, int key)
{
int begin = 0,end = n, mid = end / 2;
int result = -1;
while(begin < mid && arr[mid] != key)
{
if (key > arr[mid])
{
begin = mid;
}
else if (key < arr[mid])
{
end = mid;
}
else
{
;
}
mid = (begin + end) / 2;
}
if (arr[mid] == key)
{
result = mid;
}
return result;
}
|