c++ - 二维数组操作和二进制搜索的实现

标签 c++ arrays binary-search

我没有获得所需的适当输出。如果我将名称数作为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/

相关文章:

c++ - 为什么我们在这里需要一个 "friend"? (C++)

c++ - WINFORM C++ Managed string->unmanaged string 在与 fstream 结合使用时产生意外结果

JavaScript 循环对象以将数组附加到数组

javascript - 计算数组中有多少个具有特定名称的条目并保存以供以后使用

javascript - array.shift() 仅删除一半数组

Java arrays.binary 搜索多个匹配项?

java - 采访主题: Binary search for a range

c++ - 如果浮点范围更大,通过浮点的往返是否总是定义行为?

C++:从函数更改类成员值

c++ - 算法:改进的二进制搜索