/*
binary search
when an array is ordered ,we cna use binary_search to check whether an element in the array
Author :ljd
*/
#include<stdio.h>
int binary_search(int a[],int x,int len); //len is the length of array a
int main()
{
int a[8],i,s;
int left,mid,right;
int index;
for(i=0;i<8;i++)
{
a[i] = 8+3*i;
printf("%4d",a[i]);
}
printf("/n");
printf("Input the integer to search :/n");
if( scanf("%d",&s) !=1)
{
printf("sorry ,input wrong/n");
exit(1);
}
index=binary_search(a,s,8);
if(index!=-1)
printf("the integer exists and the index is :%d/n",index+1);
else
printf("the integer does not exists /n");
return(0);
}
int binary_search(int a[],int x,int len) //len is the length of array a
{
int i;
int left,mid,right;
left = 0;
right=len-1;
if ((x<a[left]) ||(x>a[right]))
return(-1);
while(1) //search the integer
{
if (left>right)
return(-1);
mid = (left+right)/2;
if(*(a+mid)==x)
return(mid);
else if (*(a+mid)<x)
left=mid+1;
else
right=mid-1;
}
}
binary search
when an array is ordered ,we cna use binary_search to check whether an element in the array
Author :ljd
*/
#include<stdio.h>
int binary_search(int a[],int x,int len); //len is the length of array a
int main()
{
int a[8],i,s;
int left,mid,right;
int index;
for(i=0;i<8;i++)
{
a[i] = 8+3*i;
printf("%4d",a[i]);
}
printf("/n");
printf("Input the integer to search :/n");
if( scanf("%d",&s) !=1)
{
printf("sorry ,input wrong/n");
exit(1);
}
index=binary_search(a,s,8);
if(index!=-1)
printf("the integer exists and the index is :%d/n",index+1);
else
printf("the integer does not exists /n");
return(0);
}
int binary_search(int a[],int x,int len) //len is the length of array a
{
int i;
int left,mid,right;
left = 0;
right=len-1;
if ((x<a[left]) ||(x>a[right]))
return(-1);
while(1) //search the integer
{
if (left>right)
return(-1);
mid = (left+right)/2;
if(*(a+mid)==x)
return(mid);
else if (*(a+mid)<x)
left=mid+1;
else
right=mid-1;
}
}