C++ Program: Binary Search

 

// 5 C++ program - search for a given element in an array using binary search method.


#include<iostream.h>

#include<conio.h>


class Search

{


private:

int a[10], n, ele, loc, beg, end, mid, i;

public:

void readdata( );

void bsearch( );

void display( );

};


void Search::readdata( )

{

cout<<"Enter the size of the array:"<<endl;

cin>>n;


cout<<"Enter the array elements in sorted order:"<<endl;

for(i=0;i<n;i++)

cin>>a[i];


cout<<"Enter the element to search:"<<endl;

cin>>ele;

}


void Search::bsearch( )

{

loc = -1; // Assume that element does not exist

beg = 0; // First element of the array

end = n-1; // Second element of the array

while(beg <= end)

{

mid = (beg+end)/2;

if(ele == a[mid]) // Element found at mid

{

loc = mid;

break;

}

elseif(ele < a[mid])

end = mid-1;

else

beg = mid+1;

}

}


void Search::display( )

{

if(loc == -1)

cout<<ele<<" Element does not exist...!!!";

else

cout<<ele<<" Found at Location:"<<loc+1;

}


void main( )

{


Search s;


clrscr( );

s.readdata( );

s.bsearch( );

s.display( );

getch( );

}

Comments

Popular posts from this blog

Karnataka I PUC Computer Science 2024 Study Material | SECOND PUC HANDBOOK EXAM 2025

PYTHON: Tips and Tricks