[2D数组操作和二进制搜索的实现

问题描述 投票:0回答:1

我没有获得所需的正确输出。如果我将姓名数设为4并将输入名称设为b c和d如果我搜索d。我的输出结果是一个垃圾值。

#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
int n,mid,low,high,i,found=0,loc=0;
clrscr();
char a[20][20],key[20];
cout<<"Enter the Number of names\n";
cin>>n;
cout<<"Enter the Names\n";
for(i=0;i<n;i++)
{
 cin>>a[i];
}
cout<<"Enter the name to Search of \n";
cin>>key;
low=0;high=n-1;
while(low<=high)
{
 mid=(low+high)/2;
 if(strcmp(a[mid],key)==0)
 {
  found=1;
  break;
 }
 else if(strcmp(a[mid],key)<0)
 {
  low=mid-1;
 }
 else
 high=mid+1;
}
loc=mid+1;
if(found==1)
cout<<"The name is found at location:"<<loc;
else
cout<<"Name is not found \n";
getch();
}
c++ arrays binary-search
1个回答
0
投票

错误是,如果key的值小于a [mid],则'low'的值应增加1,如果key的值小于a [mid],则应减小'low'的值。这就是为什么您得到错误输出的原因。

© www.soinside.com 2019 - 2024. All rights reserved.