-1

This is a simple binary search program, but for some reason, the program just doesn't move on after asking for the value of the key from the user. At first, I thought it is an issue with my compiler, but it still happens wherever I paste the code, and I don't know why.

#include <iostream>
using namespace std;

int binary(int arr[], int n, int k){
    int s = 0; 
    int e = n; 
    int mid = (s+e)/2; 
    while(s<=e){
        if(k==arr[mid]){
            return mid; 
        }
        else if(k>arr[mid]){
            s = mid+1; 
        }
        else if(k<arr[mid]){
            e = mid-1; 
        }
    }
    return -1;
}

int main(){
    int i, n, key;
    cin>>n; 
    int a[n];

    for(i=0;i<n;i++){
        cin>>a[i];
    }
    cout<<"Enter key:"<<endl;
    cin>>key;

    cout<< binary(a, n, key); 
}

Instead of moving on after k, the code just does nothing.

image

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 2
    *C++ program with no error* -- Your program has errors. Just because you were able to get your program to compile doesn't mean the program has no bugs. You need to debug your program. Compiling successfully only means that your program has no syntax errors. A program with no syntax errors only means that the program followed the rules of C++, nothing more, nothing less. Please read [what is a debugger?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). – PaulMcKenzie May 28 '22 at 23:10
  • 3
    `int a[n];` -- This is not valid C++. Arrays in C++ must have their size denoted by a compile-time constant, not a runtime value such as `n`. Instead, this should be `std::vector a(n);` – PaulMcKenzie May 28 '22 at 23:13

2 Answers2

0

you code is looping in the 'binary ' function

try this to see

while(s<=e){
    cout << s << e; <<<===== 

learn to use your debugger to step through the code

pm100
  • 48,078
  • 23
  • 82
  • 145
0

The middle element is found inside the loop in binary search because the search interval is reduced to half in every iteration. Your mid is not changing that is why the program is not terminating.

So final code after correction is:

#include <iostream>
using namespace std;
int binary(int arr[], int n, int k)
{
int s = 0;
int e = n;
while (s <= e)
{
    int mid = (s + e) / 2;
    if (k == arr[mid])
    {
        return mid;
    }
    else if (k > arr[mid])
    {
        s = mid + 1;
    }
    else if (k < arr[mid])
    {
        e = mid - 1;
    }
}
return -1;
}

int main()
{
int i, n, key;
cin >> n;
int a[n];

for (i = 0; i < n; i++)
{
    cin >> a[i];
}
cout << "Enter key:" << endl;
cin >> key;

cout << binary(a, n, key);
}
halfer
  • 19,824
  • 17
  • 99
  • 186