0% found this document useful (0 votes)
36 views

Binary Search

This C++ program implements a binary search algorithm to search for a key in a sorted array of integers. It defines a BinarySearch class with methods to get user input for the array elements and key, and perform the binary search. The search method recursively divides the search space in half and compares the key to the middle element until the key is found or the search space is empty.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Binary Search

This C++ program implements a binary search algorithm to search for a key in a sorted array of integers. It defines a BinarySearch class with methods to get user input for the array elements and key, and perform the binary search. The search method recursively divides the search space in half and compares the key to the middle element until the key is found or the search space is empty.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

// Name

: BinarySearch.cpp
// Author
: APOORVA MAHESHWARI
// Version
:
// Copyright
: Your copyright notice
// Description : Hello World in C++, Ansi-style
//======//===============================================
=============================
#include<iostream>
using namespace std;
class BinarySearch
{
int data[10];
int n, key;
public:
void getdata();
int search();
};
void BinarySearch::getdata()
{
int i;
cout<<"enter no. of elements n";
cin>>n;
cout<<"enter elements";
for (i=0;i<n;i++)
{
cin>>data[i];
}cout<<"enter key";
cin>>key;
}
int BinarySearch::search()
{
int imin,imax,imid,index=0;
imin=0;
imax=n-1;
while(imin<=imax)
{
imid=(imax+imin)/2;
if(key==data[imid])
{index = imid+1;
break;
}
else if(key<imid)
imax=imid-1;

else
imin=imid+1;
}
return index;
}
int main()
{
int index;
BinarySearch b;
b.getdata();
index=b.search();
if(index!=0)
cout<<"key is present at position"<<index;
else
cout<<"not found";
}

Output:
1.
enter no. of elements n5
enter elements1 2 3 4 5
enter key3
key is present at position3

2.
enter no. of elements n 5
enter elements21 22 34 56 78
enter key56
key is present at position4

3.
enter no. of elements n4
enter elements31 33 35 37
enter key37
key is present at position4

You might also like