Given a sorted array of n integers that has been rotated an unknown number of times, give an O(log n) algorithm that finds an element in the array. You may assume that the array was originally sorted in increasing order.
if(x<= a[low] && x>a[mid]) // must have = for low because the a[mid] cannot be equal but a[low] maybe
This code doesn't work for duplicate case.
#include <iostream>
int search(int a[], int low, int high, int x){
while(low <= high){
int mid = (low+high)>>1;
if(x==a[mid]) return mid;
if(a[low]> a[mid]){
if(x<= a[low] && x>a[mid]) // must have = for low
low = mid+1;
else
high = mid -1;
}
else{
if(x<a[mid] && x>=a[low]) // must have = for low
high = mid -1;
else
low = mid + 1;
}
}
return -1;
}
using namespace std;
int main()
{
cout << "Hello World" << endl;
int a[12] = {
15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14
};
int b[19] = {
2,2,2,2,2,2,2,2,3,2,2,2,2,2,2,2,2,2,2
};
cout<<search(a, 0, 11, 4)<<endl;
cout<<search(b, 0, 18, 3)<<endl;
return 0;
}