我没有获得所需的适当输出。如果我将名称数作为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();
}
最佳答案
在这里
low=mid+1
high=mid-1
否则编程在逻辑上将是错误的!
这是经过编辑的程序
#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;
int main() {
int n, mid, low, high, i, found = 0, loc = 0;
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++ - 二维数组操作和二进制搜索的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60883070/