标签:
1、 由于是有序数组,log(n)的时间查找最小值的index
1.1 一定要注意当m、r、l三个位置相同值时,无法区分左右了,所以需要在l到r区间遍历找到最小元素。
2、 看最小值index的左右两侧,是否查找值落在 [l,i] 与 [i,r] 上,在对应区间上进行二分查找
1 #include<iostream> 2 using namespace std; 3 int findminpos(int* a, int l, int r){ 4 int pos = l; 5 int min = a[l]; 6 for(int i=l+1; i<=r; i++){ 7 if( min>a[i] ){ 8 min=a[i]; 9 pos=i; 10 } 11 } 12 return pos; 13 } 14 int findBound(int *a, int r){ 15 if ( r==0 ) return 0; 16 int l = 0; 17 while(l<r){ 18 if( r-l == 1 )break; 19 int m = (l+r)>>1; 20 cout << "search at: " << m << endl; 21 if( a[m] == a[r] && a[l] == a[m] ) return findminpos(a,l,r); 22 if( a[m] > a[r] ) l = m; 23 else r = m; 24 } 25 int p = l; 26 if ( a[l] > a[r] ) p = r; 27 return r; 28 } 29 30 bool find(int *a, int s, int arrlen){ 31 if( !a ) return false; 32 int l = 0; 33 int r = arrlen-1; 34 int m = findBound(a, r); 35 cout << "start pos: " << m << endl; 36 if( s >= a[m] && s <= a[r] ) { 37 l = m; 38 } else { 39 r = m-1; 40 } 41 cout << "searching set [" << l << ","<< r << "]" << endl; 42 while ( l <= r ){ 43 m = (l+r)>>1; 44 if( a[m] == s) return true; 45 if( a[m] > s ) r = m-1; 46 else l = m + 1; 47 } 48 return false; 49 } 50 51 int main(){ 52 int a[] = {1,1,1,1,0,1,1}; 53 if(find(a, 1, 7)) { 54 cout << "find" << endl; 55 } else { 56 cout << "not found" << endl; 57 } 58 }
标签:
原文地址:http://www.cnblogs.com/25-to-life/p/4496414.html