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.
//此题很容易想到二分法。但是经平移后的值一半有序,一半不全有序。那怎么利用二分法很关键@// 首先二分法只需知道在mid的那一侧即可。
//利用mid 来找到到底是哪部有序很重要
从上图可知,由于有序,mid在1区的话,前部分有序,A[first] <= A[mid] 。从而实行二分查找!
此题要思路要清楚。
//假设默认从小到大排列!
int search(int A[], int n, int target) {
int mid,first,last;
first = 0;
last = n-1;
while(first <= last)
{
mid = (first + last)/2 ;//标准写法:MID = LEFT + ((RIGHT - LEFT) / 2);(LEFT = 0 )
if(A[mid] == target)return mid;
else if(A[first] <= A[mid])//前半部分有序,mid位于1区
{
if(target >= A[first]&&target < A[mid])//有序区间
{
last = mid - 1;
}
else
{
first = mid + 1;
}
}
else if(A[first] > A[mid] )
{
if(target > A[mid]&&A[last] >= target)//有序区间
{
first = mid + 1;
}
else
{
last = mid - 1;
}
}
}
return -1;
}
第二次:
区分了下,分别是有序 与 旋转的俩种情况。之后 根据 target在那个区间去判断,在判断 mid 是在哪个区间
int search(int A[], int n, int target)
{
if(A == NULL || n <= 0) return -1;
int left = 0;
int right = n -1 ;
int mid ;
while(left <= right)
{
mid = left + (right - left)/2;
if(A[mid] == target) return mid;
if(A[left] < A[right])//有序状况
{
if(target < A[mid])
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
else//俩头情况
{
if(A[right] == target) return right;
if(target > A[right])
{
if(A[mid] < target&&A[mid] > A[right] )
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
else
{
if (A[mid] > target &&A[mid] < A[right] )
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
}
}
return -1;
}