//Sear in Rotated Sorted Array
//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.
#include <iostream>
using namespace std;
//这题我在VS2010上能得到正常结果,而且oj上的数据[1,3],0测试也正常,一提交上去就time limite了,明明只进了while下面的第一个判断
class Solution
{
public:
int search(int a[], int n, int target)
{
if (n<2)
{
return n-1;
}
int low = 0;
int high = n-1;
int mid = 0;
while(low <= high)
{
mid = (low + high)/2;
if (a[mid] == target)
{
return mid;
}
//a[mid] <= a[high]说明mid 到 high为升序,旋转点不在这个部分,判断target是否在这个部分(mid到high),否则在其他部分
if (a[mid] <= a[high])
{
if (target <= a[high] && target > a[mid])
{
low = mid + 1;
}
else
{
high = mid;
}
}
else//a[mid] > a[high]说明low 到 mid为升序,旋转点不在这个部分,判断target是否在这个部分(low到mid),否则在其他部分
{
if (target >= a[low] && target< a[mid])
{
high = mid + 1;
}
else
{
low = mid;
}
}
}
return -1;
}
};
//重新实现了下二分查找
//int binarysearch(int A[], int n, int targe)
//{
// int low = 0;
// int high = n;
// int mid = 0;
// while(low < high)
// {
// mid = (low + high) / 2;
// if (targe < A[mid])
// {
// high = mid;
// }
// else if (targe > A[mid])
// {
// low = mid;
// }
// else
// {
// return mid;
// }
// }
//}
int main()
{
//int a[10] = {17,18,19,22,23,24, 11,12,14,15};
int a[2] = {1,3};
//cout<<binarysearch(a, 10, 14)<<endl;
Solution s;
cout<<s.search(a,2,1)<<endl;
return 0;
}