二分 : 判断条件 当a[left] <= a[mid]时,可以肯定a[left..mid]是升序的
循环有序 一共有以下两种情况
第一种
/
/
/
/
/
/
条件: (A[mid] >= A[low]) ,low~mid 二分,mid~high 递归
第二种
/
/
/
/
/
/
条件: (A[mid] < A[low]) ,low~mid 二分,mid~high 递归
1 class Solution { 2 public: 3 int binarySearch(int A[], int low, int high, int target) 4 { 5 int mid = (high+low)/2; 6 7 if(low <= high) 8 { 9 if(target == A[mid]) 10 return mid; 11 else if(target > A[mid]) 12 return binarySearch(A, mid+1, high, target); 13 else 14 return binarySearch(A, low, mid-1, target); 15 } 16 return -1; 17 } 18 19 int search(int A[], int n, int target) 20 { 21 return search(A, 0, n-1, target); 22 } 23 24 int search(int A[], int low, int high, int target) 25 { 26 27 int mid = (high+low)/2; 28 29 if(low > high) 30 return -1; 31 32 if(A[mid] == target) 33 return mid; 34 35 if(A[mid] >= A[low]) // the pivot is in the bottom half 36 { 37 if(target >= A[low] && target < A[mid]) // target in the first half 38 { 39 return binarySearch(A, low, mid-1, target); 40 } 41 else // target in the bottom half 42 { 43 return search(A, mid+1, high, target); 44 } 45 } 46 else // the pivot is in the first half 47 { 48 if(target >= A[mid+1] && target <= A[high]) // target in the bottom half 49 { 50 return binarySearch(A, mid+1, high, target); 51 } 52 else // target in the first half 53 { 54 return search(A, low, mid-1, target); 55 } 56 } 57 } 58 };
迭代:
判读条件和上面一样
1 class Solution { 2 public: 3 bool search(int A[], int n, int target) { 4 int low = 0; 5 int high = n-1; 6 int mid ; 7 8 9 while(low<=high) 10 { 11 mid= (low + high)/2; 12 13 if(A[mid]==target) 14 { 15 return true; 16 } 17 18 if(A[low]<=A[mid]) // the pivot is in the bottom half 19 { 20 if(A[low]<=target && target < A[mid]) //target in the first half 21 high = mid-1; 22 else 23 low = mid+1;//target in the bottom half 24 } 25 else // the pivot is in the first half 26 { 27 if(A[mid] < target && target <= A[high])// the pivot is in the first half 28 low = mid+1; 29 else //target in the first half 30 high = mid-1; 31 } 32 33 } 34 return false; 35 36 } 37 };