#include<stdio.h>
#include<iostream>
using namespace std;
int MinInOrder(int *a,int low,int high)
{
int result=a[low];
for(int i=low+1;i<=high&&a[i]<result;++i)
result=a[i];
return result;
}
int Min(int *a,int length)
{
if(a==NULL||length<=0)
throw new std::exception("Invalid parameters");
for(int low=0,high=length-1,mid=low;a[low]>=a[high];)
{
if(high-low==1)
return a[high];
mid=(low+high)/2;
if(a[low]==a[high]&&a[mid]==a[low])
return MinInOrder(a,low,high);
if(a[mid]>=a[low])
low=mid;
if(a[mid]<=a[high])
high=mid;
}
}
void main()
{
int a[6]={3,4,5,6,1,2};
printf("旋转数组{3,4,5,6,1,2}的最小数字是:%d\n",Min(a,6));
int b[7]={1,2,0,1,1,1,1};
printf("旋转数组{1,2,0,1,1,1,1}的最小数字是:%d\n",Min(b,6));
printf("空指针测试:%d\n",Min(NULL,0));
}
剑指offer--面试题11:旋转数组的最小数字
最新推荐文章于 2024-01-05 14:32:14 发布