Home > Software engineering >  To search an element using Binary Search
To search an element using Binary Search

Time:12-12

I tried the following code for searching an element in the array using binary search without using the function, but it does not work as it stops just after asking the Number I am searching for in the array. Not able to figure out, As exactly where I am mistaken. Using Visual Studio Code.

int main()
{

    int arr[10],n,num,mid,l=0,h=n-1,i;
    cout<<"Enter the number of elements in the array\n";
        cin>>n;
        cout<<"Enter the elements of the array\n";
        for(int i=0;i<n;i  )
        {
            cin>>arr[i];
        }
    cout<<"Enter the number to be searched.\n";
    cin>>num;
    
    while(l<=h)
    {
        mid=(l h)/2;
        if(arr[mid]==num)
        {
            cout<<"Number found at "<<mid<<"\n";
            break;
        }
        if(arr[mid]>num)
        {
            h=mid-1;
        }
        else
        {
            l=mid 1;
        }
    }
    if(l>h)
    {
    cout<<"Number not found.\n";
    }

    return 0;
}

CodePudding user response:

You have initialized h = n-1 before initializing n. Hence, we have Undefined behaviour.

#include <iostream>

using namespace std;

int main()
{

    int arr[10], n, num , mid, l, h, i;
    cout<<"Enter the number of elements in the array\n";
    cin>>n;
    cout<<"Enter the elements of the array\n";
    for(int i=0;i<n;i  )
    {
        cin>>arr[i];
    }
    cout<<"Enter the number to be searched.\n";
    cin>>num;
    l = 0;
    h = n-1;
    while(l <= h)
    {
        mid = (l h)/2;
        if(arr[mid] == num)
        {
            cout<<"Number found at index "<<mid<<"\n";
            break;
        }
        if(arr[mid] > num)
        {
            h = mid-1;
        }
        else
        {
            l = mid 1;
        }
    }
    if(l > h)
    {
        cout<<"Number not found.\n";
    }

    return 0;
}

CodePudding user response:

so here is my code -->

#include <iostream>
#include <cmath>
using namespace std;
int binarySearch(int arr[] , int first , int last ,int value){
    if(last >= first){
    int mid = first   (last-first)/2;
    if(arr[mid] == value){
        return mid;
    }
    if(value > arr[mid]){
        return binarySearch(arr , mid 1 , last , value);
    }else if(value< arr[mid]){
        return binarySearch(arr , first , mid-1 , value);
    }
    }

    return -1;

}
int main(){
    int n; cin >> n;
    int arr[n];
    for(int i=0 ; i<n ; i  ){
        cin >> arr[i];
    } // requires sorted array
    int value ; cin >> value;
    cout << binarySearch(arr , 0 , n-1 , value);

    return 0;
}
  •  Tags:  
  • c
  • Related