C程式設計語言 Exercise 3-1
阿新 • • 發佈:2019-02-13
Exercise 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.
the price of more tests outside.) Write a version with only one test inside the loop and
measure the difference in run-time.
#include "stdio.h" #include "time.h" #define MAX_LENGTH 2000000 int BinSearch1(int,int[],int); int BinSearch2(int,int[],int); int main(){ int v[MAX_LENGTH] = {0}; int i = 0; for (i = 0;i < MAX_LENGTH;i++) { v[i] = i; } clock_t stStartTime = clock(); for (i = 0;i < MAX_LENGTH;i++) { BinSearch1(i,v,sizeof(v)/sizeof(*v)); } printf("BinSearch1==>%f\n",((double)(clock() - stStartTime)) / CLOCKS_PER_SEC); stStartTime = clock(); for (i = 0;i < MAX_LENGTH;i++) { BinSearch2(i,v,sizeof(v)/sizeof(*v)); } printf("BinSearch2==>%f\n",((double)(clock() - stStartTime)) / CLOCKS_PER_SEC); return 0; } int BinSearch1(int x,int v[],int n) { int start = 0; int end = n - 1; int middle = 0; while(start <= end) { middle = (start + end) / 2; if(v[middle] < x) { start = middle + 1; } else if(v[middle] > x){ end = middle - 1; } else { return middle; } } return -1; } int BinSearch2(int x,int v[],int n){ int start = 0; int end = n - 1; int middle = 0; while(start <= end && v[middle] != x){ middle = (start + end) / 2; if(v[middle] < x) { start = middle + 1; } else{ end = middle - 1; } } return v[middle] == x ? middle: -1; }