0% found this document useful (0 votes)
8 views1 page

Binary Search Implementation in C++

The document contains a C++ program that implements a binary search algorithm to find an element in a user-defined array. It prompts the user to enter the number of elements and the elements themselves, then asks for a key to search for in the array. If the key is found, it returns the index; otherwise, it indicates that the element is not found.

Uploaded by

gauravpawar2640
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views1 page

Binary Search Implementation in C++

The document contains a C++ program that implements a binary search algorithm to find an element in a user-defined array. It prompts the user to enter the number of elements and the elements themselves, then asks for a key to search for in the array. If the key is found, it returns the index; otherwise, it indicates that the element is not found.

Uploaded by

gauravpawar2640
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

#include <iostream>

using namespace std;

int bs(int arr[],int size , int key)


{
int low = 0;
int high = size -1;
while (low<=high)
{
int mid=(low+high)/2;
if (arr[mid]==key)
{
return mid;
}
else if (arr[mid]<key)
{
low=mid+1;
}
else
{
high = mid-1;
}
}
return -1;
}
int main()
{
int n;
cout<<"ENTER THE NUMBER OF ELEMENTS:";
cin>>n;
int arr[n];
cout<<"ENTER "<<n<<" Elements: \n";
for (int i=0;i<n;i++)
{
cin>>arr[i];
}
int size = sizeof(arr)/sizeof(arr[0]);
int key;
cout<<"ENTER THE ELEMNENTS TO SEARCH:";
cin>>key;

int result = bs(arr,size , key);


if (result==-1){
cout<<"ELEMENT NOT FOUND "<<endl;
}
else
{
cout<<"ELEMENT FOUND AT INDEX:"<<result<<endl;
}
return 0;
}

You might also like