Anurag Hale
Anurag Hale

Reputation: 135

how is the output going to get displayed?

i was writing a c++ code for performing binary search in an array,but am unable to wield the desired output. when execute the code, i ma getting a never ending output, what may be the reason behind this?

#include <iostream>
using namespace std;

void Binary(int arr[], int n, int key)
{
  int s = 0;
  int e = n - 1;

  while (s <= e) {
    int mid = (s + e) / 2;

    if (arr[mid] == key) {
      cout << "Element Found At Index No. " << mid;
    } else if (arr[mid] > key) {
      e = mid - 1;
    } else {
      s = mid + 1;
    }
  }
}

int main()
{
  int n;
  cin >> n;

  int arr[n];
  for (int i = 0; i < n; i++) {
    cin >> arr[i];
  }

  int key;
  cout << "Enter element to be searched!";
  cin >> key;

  Binary(arr, n, key);

  return 0;
}

Upvotes: 0

Views: 27

Answers (2)

Mital Vora
Mital Vora

Reputation: 2249

Answer provided by @1201ProgramAlarm is the right fix. Adding few minor changes:

  • Instead of using namespace std; it would be better to explicitly provide the scope resolution for std::cin and std::cout

  • Providing some more print statements while entering the array elements.

     #include <iostream>
    
     void Binary(int arr[], int n, int key)
     {
       int s = 0;
       int e = n - 1;
    
       while (s <= e) {
         int mid = (s + e) / 2;
    
         if (arr[mid] == key) {
           std::cout << "Element Found At Index No. " << mid;
           break;
         } else if (arr[mid] > key) {
           e = mid - 1;
         } else {
           s = mid + 1;
         }
       }
     }
    
     int main()
     {
       int n;
       std::cout << "Enter Number of elements in the array: ";
       std::cin >> n;
    
       int arr[n];
       std::cout << "Enter " << n << " sorted array elements: ";
       for (int i = 0; i < n; i++) {
         std::cin >> arr[i];
       }
    
       int key;
       std::cout << "Enter element to be searched!";
       std::cin >> key;
    
       Binary(arr, n, key);
    
       return 0;
     }
    

Upvotes: 0

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32727

After you find your element, you generate output but never exit the loop or change either of the values that the loop condition checks.

Simply break out of the loop (or return from the function) after showing your output:

if (arr[mid] == key) {
  cout << "Element Found At Index No. " << mid;
  break;
}

Upvotes: 1

Related Questions