Search Your Query

Custom Search

Tuesday, 24 May 2011

Binary Search Programe (C/C++ Solved Programs)


#include <iostream.h>

void main()
{
    int num[10] ;
    int beg=0 , end=10 , mid=0, l=0, item=0 , t=0;

    cout << "Enter ten numbers: " << endl;

    for ( int i=0 ; i<10 ; i++ )
        cin >> num[i];
   
    for ( i=0 ; i<10 ; i++ )
    {
        for (int j=0 ; j<10-i ; j++)
        {
            if (num[j]>num[j+1])
            {
                t = num[j];
                num[j] = num[j+1];
                num[j+1] = t;
            }
        }
    }
    cout << "Numbers in ascending order: " << endl;
    for ( i=0 ; i< 10 ; i++)
        cout << num[i] << " ";
    cout << endl ;

    cout << "Enter the number to search: " ;
    cin >> item;

    mid = int((beg+end)/2);

    while (beg<=end && num[mid]!=item)
    {
        if (item < num[mid])
            end = mid - 1;
        else
            beg = mid + 1;

        mid = int ((beg + end)/2);
    }

    if ( num[mid] == item)
        l= mid;
    else
        l= 0;

    if (l)
        cout << "Number is present at the location " << l+1 << "." << endl << endl;
    else
        cout << "Number not found." << endl << endl;
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...