Binary search in C++.

//There is a simple program for implementing binary search algorithm

//Remember that binary search algorithm can only be implemented in a sorted array.

 

#include<iostream>
#include<cstdio>

using namespace std;

int main(){

    int n;

    cout << "How many numbers:";
    cin >> n;

    int a[n],count;

    for(count = 0; count < n; count++)
    {
        char c;

        scanf("%d%c",&a[count],&c);

        if(c=='\n')
            break;

    }

    int lower_bound = 0, upper_bound = count, mid = (int) count / 2, number;

    cout << "Which number do you want to search:";
    cin >> number;

    bool x=true;

    while(lower_bound<upper_bound)
    {

        if(a[mid] == number)
        {
            cout<<"data found\n";

            x=false;
            break;
        }

        else if(a[mid] > number)
        {
            upper_bound = mid-1;

            mid = (int)((lower_bound+upper_bound)/2);
        }

        else if(a[mid]<number)
        {

            lower_bound = mid+1;

            mid = (int)((lower_bound+upper_bound)/2);

        }
    }


    if(x)
        cout << "Data not found\n";

    return 0;
}


No comments:

Post a Comment

Kruskal Algorithm

Minimum Cost Spanning Tree By Kruskal Algorithm using priority_queue in c++ #include<bits/stdc++.h> using namespace std; typedef p...