#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; }
时间: 2024-10-13 12:06:48