《c程序设计语言》-3.1 判断语句多少影响时间
#include <stdio.h> #define Num 1000000 /* int binsearch(int x,int v[],int n) { int low,high,mid; low = 0; high = n-1; while(low <= high) { mid = (low + high) / 2; if(x > v[mid]) high = mid - 1; else if(x < v[mid]) low = mid + 1; else return mid; } return 0; } */ int binsearch(int x,int c[],int n) { int low = 0,high = n-1; int mid; mid = ( low + high ) / 2; while( low <= high && c[mid] != x ) { if( c[mid] < x ) high = mid - 1; else low = mid + 1; mid = ( low + high ) / 2; } if( c[mid] == x ) return mid; return 0; } int main() { int c[Num] = {0}; int i,j = Num; int x = 7; for(i = 0;i < Num;i++) { c[i] = j; j--; } printf("%d\n",binsearch(x,c,Num)); return 0; }
亲测,第二种方法节省时间。判断语句少了,就节省时间了。