9/10/2017,简写一个封装好的二分查找,适用于C/C++
正文如下:
int Binary_search(DateType *a,DateType K,const DateType n) { int beg = 1,end = n; mid = beg + (end - beg)/2; while((mid != end) && (a[mid] != K)) { if(a[mid] < K) beg = mid + 1; else end = mid; mid = beg + (end -beg)/2; } if(a[mid] == K) return mid; else return -1; }
最坏情况是a[1] or a[n] = k,假设需要二分m次,则有:
n/2 n/4 n/8 ... n/(2^m) = 1;
得2^m = n,所以时间复杂度为O(lg(n))
图解如下:
(图片来源于CSDN博主皓皓松)
时间: 2024-10-09 21:58:07