Binary Search.
#include<iostream>
using namespace std;
void inputArray(int a[],int n);
void bubbleSort(int a[],int n);
int binarySearch(int a[],int n,int key);
int main()
{
int a[250];
int n;
int key;
int ans;
cout<<"\nENTER THE SIZE OF AN ARRAY: ";
cin>>n;
inputArray(a,n);
bubbleSort(a,n);
cout<<"\n enter the key: ";
cin>>key;
ans = binarySearch(a,n,key);
if(ans!=-1)
{
cout<<" \nElement is found. ";
}
else
cout<<" \nElement is not found";
}
void inputArray(int a[],int n)
{
for(int i=0;i<n;i++)
{
cout<<"\nENTER THE AN ARRAY: ";
cin>>a[i];
}
}
void bubbleSort(int a[],int n)
{
int temp;
for(int i=0;i<n-1;i++)
{
for(int j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
int binarySearch(int a[],int n,int key)
{
int low;
int high = n-1;
while(low<=high)
{
int mid = (low+high)/2;
if(a[mid]==key)
return mid;
else if(a[mid]<key)
low = mid+1;
else
high = mid - 1;
}
return -1;
}
0 Comments