My Blog List

Friday, December 6, 2019

Binary search using cpp.

Binary Search using cpp.

In this tutorial we learn how to search element from given array.This technique is best technique for searching element in large amount of data is given.This techniques is based on the Divide and Conquer.But main condition for this technique is that the data given input is sorted.This approach divide the array in two part and then search the element where the small by middle element or greater.


Code:


#include<iostream.h>
#include<conio.h>
void main()
{
    int n,i,arr[50],search,first,last,middle;
    clrscr();
    cout<<"\nEnter total number of element:";
    cin>>n;
    cout<<"\nEnter the element:";
    for(i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    cout<<"\nEnter searchable element:";
    cin>>search;
    first=0;
    last=n-1;
    middle=(first+last)/2;
    while(first<=last)
    {
        if(arr[middle]<search)
        {
            first=middle+1;
        }
        else if(arr[middle]==search)
        {
            cout<<search<<" found at position:"<<middle+1<<"\n";
            break;
        }
        else
        {
            last=middle-1;
        }
        middle=(first+last)/2;
    }
    if(first>last)
    {
        cout<<"\nElement not found:";
    }
    getch();
}





OUTPUT:



for video demonstration follow:

https://youtu.be/qFpjuqX1gAQ

No comments:

Post a Comment

Multiple Inheritance in C++.

     In this tutorial Multiple Inheritance in c++. On the basis of Inheritance concept the another type of inheritance is the Multiple I...