Манипулирование двумерным массивом и реализация бинарного поиска - PullRequest
5 голосов
/ 27 марта 2020

Я не получаю правильный вывод, как мне нужно. Если я беру количество имен как 4 и вводим имена как ab 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();
}

Ответы [ 2 ]

4 голосов
/ 29 марта 2020

Этот алгоритм поможет вам

1.Start
2.(Input the number of names in the list) 
   Input n
3.(Input names in the list) 
   For i:0to n repeat input each names and store it in array 'a'
   End for 
4.(Input the key to be searched) 
   Input key 
5.initailization 
   Low -0
   High -n-1
6.while(low<=high) 
(calculate the midpoint for equal partition) 
Mid -(low+high)/2
If(strcmp(key,a(mid))<0)
(change index to search upper subbarray) 
Low -mid+1
else 
(change high index to search lower subarray) 
High -mid-1
End if 
7.if(f=1) 
Print successful search 
Else print unsuccessful search 
End if
8.stop
4 голосов
/ 29 марта 2020

здесь должно быть

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();
}

надеюсь, это поможет вам.

...