# [算法]各种二分查找

1，给定一个有序数组values，求任意一个i使得values[i]等于v,不存在返回-1

int search(int* values,int len,int key)
{
if(!values || len <=0) return -1;
int low=0;
int high=len-1;
while(low<=high)
{
int mid =(low+high)/2;
if(values[mid]==key) return mid;
else if(values[mid]>key) high=mid-1;
else low = mid +1;
}
return -1;
}

2,给定一个有序数组values，求最小的i使得values[i]等于v,不存在返回-1

int searchFirst(int * values,int len,int key)
{
if(!values || len <=0) return -1;
int low=0;
int high=len-1;
while(low<=high)
{
int mid =(low+high)/2;
if(values[mid]==key)
{
if(mid==0) return mid;
else if(values[mid-1]<key) return mid;
else high=mid-1;
}
else if (values[mid]>key) high=mid-1;
else low=mid+1;
}
return -1;
}

3，给定一个有序数组values，求最大的i使得values[i]等于v,不存在返回-1

int searchLast(int* values,int len,int key)
{
if(!values || len <=0) return -1;
int low=0;
int high=len-1;
while(low<=high)
{
int mid =(low+high)/2;
if(values[mid]==key)
{
if(mid==len-1) return mid;
else if(values[mid+1]>key) return mid;
else low=mid+1;
}
else if (values[mid]>key) high=mid-1;
else low=mid+1;
}
return -1;
}

4，给定一个有序数组values，求最大的i使得values[i]小于v,不存在返回-1

int searchLargestSmallThan(int* values,int len,int key)
{
if(!values || len <=0) return -1;

int low=0,high=len-1;
while(low <= high){
int mid = (low+high)/2;
if(values[mid]>=key) high=mid-1;
else{
if(mid<len-1 && values[mid+1]>=key) return mid;
else
low=mid+1;
}
}
return -1;
}

4，给定一个有序数组values，求最小的i使得values[i]大于v,不存在返回-1

int searchSmallestLargeThan(int* values, int len,int key)
{
if(!values || len <=0) return -1;
int low=0,high=len-1;
while(low <= high){
int mid = (low+high)/2;
if(values[mid]<=key) low=mid+1;
else{
if(mid>0 && values[mid-1]<=key) return mid;
else
high=mid-1;
}
}
return -1;
}

5，数组A绝对值有序，绝对值相同的负值出现在正值前面，返回key出现的第一个位置

int searchInAbsOrder(int* values,int len,int key)
{
int i=0,j=len-1;
while(i<=j)
{
int mid=(i+j)/2;
if(values[mid]==key)
{
if(mid==0) return mid;
else if(values[mid]>values[mid-1])
{
return mid;
}
else
{
j=mid-1;
}
}
else if(values[mid]==-key)
{
if(key>=0)
{
i=mid+1;
}
else
{
j=mid-1;
}
}
else if(abs(values[mid])>abs(key))
{
j=mid-1;
}
else
{
i=mid+1;
}
}
return -1;
}

posted @ 2014-10-20 10:52 orchid 阅读(...) 评论(...) 编辑 收藏