practice 3-1:Our binary search makes two tests inside the loop,when one would suffice (at the price of more tests outside).Write a version with only one test inside the loop and measure the difference in run-time.
#include
#include
#define MAX_ELEMENT 20000
int binsearch1(int x,int v[],int n)
{
int low,high,mid;
low=0;
high=n-1;
while(low<=high){
mid=(low+high)/2;
if(x
high=mid-1;
else if(x>v[mid])
low=mid+1;
else
return mid;
}
return -1;
}
int binsearch2(int x,int v[],int n)
{
int low,high,mid;
low=0;
high=n-1;
mid=(low+high)/2;
while(low<=high&&x!=v[mid])
{
if(x
high=mid-1;
else
low=mid+1;
mid=(low+high)/2;
}
if(x==v[mid])
return mid;
else
return -1;
}
main()
{
int testdata[MAX_ELEMENT];
int index;
int n=-1;
int i;
clock_t time_taken;
for(i=0;i
testdata[i]=i;
for(i=0,time_taken=clock();i<10000;++i)
{
index=binsearch1(n,testdata,MAX_ELEMENT);
}
time_taken=clock()-time_taken;
if(index<0)
printf("Element %d not found.\n",n);
else
printf("Element %d found at index %d.\n",n,index);
printf("binsearch1() took %lu clocks (%lu seconds)\n",(unsigned long)time_taken,(unsigned long)time_taken/CLOCKS_PER_SEC);
for(i=0,time_taken=clock();i<10000;++i)
{
index=binsearch2(n,testdata,MAX_ELEMENT);
}
time_taken=clock()-time_taken;
if(index<0)
printf("Element %d not found.\n",n);
else
printf("Element %d found at index %d.\n",n,index);
printf("binsearch2() took %lu clocks (%lu seconds)\n",(unsigned long)time_taken,(unsigned long)time_taken/CLOCKS_PER_SEC);
return 0;
}
conclusion: I have to admit how difficult to understand these code, especially the part of time calculate .However,we need believe in that,more attempts, more progress.So just try it and take some time to assimilate it.