标签:style blog color ar sp div log bs as
//循环实现
int binsearch(int* a, int i, int j, int goal){ if(a == NULL) return -1; while(i<=j){ int mid = (i + j)/2; if(a[mid] == goal){ return mid; } else if(a[mid] > goal){ j = mid - 1; } else if(a[mid] < goal){ i = mid + 1; } } return -1; }
递归实现
int binsearch(int* a, int i, int j, int goal){ if(a == NULL) return -1; if(i > j) return -1; int mid = (i + j)/2; if(a[mid] == goal){ return mid; } else if(a[mid] > goal){ return binsearch(a,i,mid-1,goal); } else if(a[mid] < goal){ return binsearch(a,mid+1,j,goal); } }
标签:style blog color ar sp div log bs as
原文地址:http://www.cnblogs.com/Nison/p/4025820.html