首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

折半查找解决方案

2013-10-21 
折半查找请问折半查找没有要查找的值怎么写 int zheban(int a[],int r,int l,int x) { if(rl) return 0

折半查找
请问折半查找没有要查找的值怎么写
 
int zheban(int a[],int r,int l,int x)
 {
 if(r==l)
 return 0;
 else
 {
 int mid=(r+l)/2;
 if(x<a[mid])
 return zheban(a,r,mid,x);
 if(x>a[mid])
 return zheban(a,mid+1,l,x);
 else
 return mid;
 }

 }
谢谢
[解决办法]
花了几分钟,写了一个程序,没有考虑健壮性等问题。
程序如下:

int zheban(int *da,int num,int low,int high)//如果成功则返回位置,否则返回-1
{
int mod=low;
int len=high-low;
mod=(low+high)/2;
if(len<0)
return -1;
else if(len==0)
return mod;
if(da[mod]>num)
{
return zheban(da,num,low,mod-1);
}
else if(da[mod]<num)
{
return zheban(da,num,mod+1,high);
}
else
return mod;
}

利用数组:int data[10]={3,8,10,19,54,65,65,77,98,99};测试数据为:55,54,3,99,65.都能返回正确标示,程序不完整,仅实现了你所要求的。
[解决办法]
// ZheBan.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;
int ZheBan(int array[],int length,int goal);

int _tmain(int argc, _TCHAR* argv[])
{
int array[10]={1,3,5,7,20,24,25,30,34,35};
int length=10;
int location1=ZheBan(array,length,20);
int location2=ZheBan(array,length,30);
int location3=ZheBan(array,length,100);
cout<<location1<<endl;//位置
cout<<location2<<endl;
cout<<location3<<endl;//输出位置为-1表示没有
return 0;
}
int ZheBan(int array[],int length,int goal)
{
//array数组升序
//
int mid,start,end;
start=0;
end=length-1;
while(end>start)
{
mid=(start+end)/2;
if (array[mid]>goal)
{
end=mid-1;
}
else if (array[mid]<goal)
{
start=mid+1;
}
else
{
return mid;
}
}
return -1;//没有找到,没有该数据

}
//测试可用
[解决办法]
网上很多很多

热点排行