首页 > 代码库 > 求旋转有序数组的最小值和在旋转数组中查找

求旋转有序数组的最小值和在旋转数组中查找

#include<iostream>

using namespace std;

int find2(int A[],int n)
{
  int high=n-1;
  int low =0;
  int mid;
  while(A[high]<=A[low])
  {
    if(high-low==1)
    {
         mid=high;
         break;
    }   
    mid=low+(high-low)/2;
    if(A[mid]>=A[low])
    {
     low=mid;
    }else if(A[mid]<=A[high]){
       high=mid;
    }

  }
   return A[mid];
}
int find(int A[],int n,int value)
{
  int low=0;
  int high=n-1;
  int mid;
  while(low<=high)
  {
   mid=low+(high-low)/2;
   if(A[mid]==value)
    return mid;
   if(A[low]<=A[mid])//左边有序
   {
     if(A[mid]>value&&value>=A[low])
     {
       high=mid-1;
     }else{
       low=mid+1;
     }
   }else if(A[mid]<=A[high])//右边有序
   {
       if(A[mid]<value&&A[high]>=value)
       {
        low=mid+1;
       }else{
        high=low-1;
      }
   }
   
  }
return (A[mid]==value) ? mid : -1;
}
int main()
{
    int a[]={4,5,6,1,2,3};
    cout<<find(a,6,3)<<endl;
    cout<<find2(a,6)<<endl;
}

求旋转有序数组的最小值和在旋转数组中查找