2014年05月15日

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值