描述
Suppose a sorted array is rotated at some pivot unknown to you beforehand.(i.e.,0 1 2 4 5 6 7might 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.
Suppose a sorted array is rotated at some pivot unknown to you beforehand.(i.e.,0 1 2 4 5 6 7might 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;
int FindNumRotatedArray(int a[], int n, int value)
{
if (a == NULL || n <= 0)
return -1;
int begin = 0;
int end = n - 1;
while (begin <= end)
{
int mid = (begin + end) / 2;
if (a[mid] == value)
return mid;
if (a[mid] >= a[begin])
{
if (a[begin]<=value&&value < a[mid])
end = mid-1;
else
begin = mid + 1;
}
else
{
if (a[mid] < value &&value <= a[end])
begin = mid + 1;
else
end = mid-1;
}
}
return -1;
}
void main()
{
const int n = 10;
int value = 6;
int a[10] = { 6,7,9,10,13,24,-1,0,3,4 };
int index = FindNumRotatedArray(a, n,value);
if (index != -1)
cout << a[index] << endl;
}