2014年05月15日

来源:互联网 发布:呱呱社区软件 编辑:程序博客网 时间:2024/04/19 19:22

practice 3-1:Our binary search makes two tests insidethe loop,when one would suffice (at the price of more testsoutside).Write a version with only one test inside the loop andmeasure 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
   returnmid;
 }
 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 notfound.\n",n);
 else
  printf("Element %d found atindex %d.\n",n,index);
 printf("binsearch1() took %lu clocks (%luseconds)\n",(unsigned long)time_taken,(unsignedlong)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 notfound.\n",n);
 else
  printf("Element %d found atindex %d.\n",n,index);
 printf("binsearch2() took %lu clocks (%luseconds)\n",(unsigned long)time_taken,(unsignedlong)time_taken/CLOCKS_PER_SEC);

 return 0;
}

 

conclusion: I have to admit how difficult to understandthese code, especially the part of time calculate .However,we needbelieve in that,more attempts, more progress.So just try it and take sometime to assimilate it.

0 0
原创粉丝点击