您的位置:首页 > 其它

二叉查找各类情况总结

2015-08-21 15:14 204 查看

1. 给定一个有序(不降序)数组arr,求最大的i使得arr[i]等于v,不存在则返回-1

int bisearch(char** arr ,int b,int e,char* v)
{
int minIndex=b,maxIndex=e,midIndex;

while(minIndex < maxIndex-1)//防止midIndex=3,maxIndex=4是陷入死循环
{
midIndex = minIndex+(maxIndex-minIndex)/2;

if(strcmp(arr[midIndex],v)<=0)  //midIndex=3,maxIndex=4是陷入死循环
{
minIndex=midIndex;
}
else
{
maxIndex = midIndex;    //不需要midIndex-1,防止minIndex==maxIndex
}
}
if(!strcmp(arr[maxIndex],v))
{
return maxIndex;
}
else if(!strcmp(arr[minIndex],v))
{
return minIndex;
}
else
{
return -1;
}
}


2.给定一个有序(不降序)数组arr,求任意一个i使得arr[i]等于v,不存在返回-1

int bisearch2(char** arr,int b,int e,char* v)
{
int minIndex=b,maxIndex=e,midIndex;
while(minIndex <=maxIndex)
{
midIndex = minIndex+(maxIndex-minIndex)/2;
if(strcmp(arr[midIndex],v)<0)
{
minIndex=midIndex+1;
}
else if(strcmp(arr[midIndex],v)>0)
{
maxIndex=midIndex-1;
}
else
{
return midIndex;
}
}
return -1;
}


3. 给定一个有序(不降序)数组arr,求最小的i使得arr[i]等于v,不存在返回-1

int bisearch3(char** arr,int b,int e,char* v)
{
int minIndex=b,maxIndex=e,midIndex;
while(minIndex<maxIndex-1)
{
midIndex=minIndex+(maxIndex-minIndex)/2;
if(strcmp(arr[midIndex],v)>=0)
{
maxIndex=midIndex;
}
else
{
minIndex=midIndex+1;
}
}
if(!strcmp(arr[minIndex],v))
{
return minIndex;
}
else if(!strcmp(arr[maxIndex],v))
{
return maxIndex;
}
else
return -1;
}


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

int bisearch4(char** arr,int b,int e,char* v)
{
int minIndex=b,maxIndex=e,midIndex;
while(minIndex<maxIndex-1)
{
midIndex=minIndex+(maxIndex-minIndex)/2;
if(strcmp(arr[midIndex],v)>=0)
{
maxIndex=midIndex-1;
}
else
{
minIndex=midIndex;
}
}
if(strcmp(arr[maxIndex],v)<0)
{
return maxIndex;
}
else if(strcmp(arr[minIndex],v)<0)
{
return minIndex;
}
else
return -1;
}


5. 给定一个有序(不降序)数组arr,求最小的i使得arr[i]大于v,不存在返回-1

int bisearch5(char** arr,int b,int e,char* v)
{
int minIndex=b,maxIndex=e,midIndex;
while(minIndex<maxIndex-1)
{
midIndex=minIndex+(maxIndex-minIndex)/2;
if(strcmp(arr[midIndex],v)<=0)
{
minIndex=midIndex+1;
}
else
{
maxIndex=midIndex;
}
}
if(strcmp(arr[minIndex],v)>0)
{
return minIndex;
}
else if(strcmp(arr[maxIndex],v)>0)
{
return maxIndex;
}
else
{
return -1;
}
}


主程序

#include<iostream>
using namespace std;
int main()
{
char* arr[]={"a","boy","good","is","is","this","this","very","very","very"};
char* object="is";
cout<<bisearch(arr,0,9,object)<<endl;
cout<<bisearch2(arr,0,9,object)<<endl;
cout<<bisearch3(arr,0,9,object)<<endl;
cout<<bisearch4(arr,0,9,object)<<endl;
cout<<bisearch5(arr,0,9,object)<<endl;
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: