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
给出一个n个整数的已排序的数组,这个数组被旋转(翻转)未知的次数
分析:这个数组被rotated了未知次,那么把这个数组分成两段考虑,前半段这个数组是递增排序的,后半段这个数组也是递增排序的,具体这个分段的地方就依赖于翻转的次数了。这一点比较关键
下面这个算法是solution中给出的,但是有缺陷如果数组中有相同元素的话,这个算法就失效了
#include<iostream> using namespace std; //l means lowerbound,u means upperbound int search(int a[], int l, int u, int x){ while(l<=u){ int m=(l+u)/2; if(x==a[m]) return m; else if(a[l]<=a[m]){ if(x>a[m]) l=m+1; else if(x>=a[l]) u=m-1; else l=m+1; } else if(x<a[m]) u=m-1; else if(x<=a[u]) l=m+1; else u=m-1; } return -1; } int main(){ int a[]={15,16,19,20,25,1,3,4,5,7,10,14}; cout<<search(a,0,11,5); system("pause"); return 0; }