Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7
might become 4 5 6 7 0 1 2
).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
[Solution]
1) A[middle] > A[left], 说明 A[left, middle]有序。
2) A[middle] < A[left], 说明 A[middle, right]有序。
1 int search(int A[], int n, int target) 2 { 3 int left = 0, right = n - 1, middle; 4 5 while (left <= right) 6 { 7 middle = (left + right) >> 1; 8 if (A[middle] == target) 9 return middle; 10 if (A[middle] > A[left]) 11 { 12 if (target >= A[left] && target < A[middle]) 13 right = middle - 1; 14 else 15 left = middle + 1; 16 } 17 else if (A[middle] < A[left]) 18 { 19 if (target > A[middle] && target <= A[right]) 20 left = middle + 1; 21 else 22 right = middle - 1; 23 } 24 else 25 { 26 middle = right; 27 break; 28 } 29 } 30 31 return A[middle] == target ? middle : -1; 32 }
时间: 2024-10-22 02:45:57