2.1.3 Search in Rotated Sorted Array
其中无重复部分
#include <stdio.h>
void main()
{
int a[7]={4,5,6,7,0,1,2};
int result = SRSA(a,7,6);
printf("%d",result);
}
int SRSA(int A[],int length,int target)
{
int first=0;
int last=length;
int mid=0;
while(first<last)
{
mid=(first+last)/2;
if(A[mid]==target)
return mid;
if(A[first]<=A[mid])
{
if(A[first]<=target && target<A[mid])
{
last=mid;
}else
{
first=mid+1;
}
}else
{
if(A[mid]<target && target<=A[last-1])
{
first=mid+1;
}else
{
last=mid;
}
}
}
return -1;
}
2.1.4 Search in Rotated Sorted Array II
其中有重复部分
#include <stdio.h>
void main()
{
int a[5]={1,3,1,1,1};
int result = SRSA(a,5,1);
printf("%d",result);
}
int SRSA(int a[],int length,int target)
{
int first=0;
int last=length;
int mid=0;
while(first!=last)
{
mid=(first+last)/2;
if(a[mid]==target)
{
return mid;
}
if(a[first]==a[mid])
{
first++;
continue;
}
if(a[first]<a[mid])
{
if(a[first]<=target&&target<a[mid])
{
last=mid;
}else
{
first=mid+1;
}
}else
{
if(a[mid]<target&&target<=a[last-1])
{
first=mid+1;
}else
{
last=mid;
}
}
}
return -1;
}
转载于:https://blog.51cto.com/wukong0716/1713843