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

Programme For Binary Search in Array

This document contains code for a binary search algorithm in C++. It defines a main function that gets array elements from the user, calls a binary search function to search for a given value, and prints the result. The binary search function takes the array, size, and value as parameters, performs a binary search to find the index of the value, and returns the index or -1 if not found.

Uploaded by

Suraj Kundu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Programme For Binary Search in Array

This document contains code for a binary search algorithm in C++. It defines a main function that gets array elements from the user, calls a binary search function to search for a given value, and prints the result. The binary search function takes the array, size, and value as parameters, performs a binary search to find the index of the value, and returns the index or -1 if not found.

Uploaded by

Suraj Kundu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

17.

PROGRAMME FOR BINARY SEARCH


IN ARRAY
#include<iostream.h>
#include<conio.h>
int binary(int[],int,int);
int main()
{

int a[20],n,index,i,val;
clrscr();
cout<<"Enter number of elements: ";
cin>>n;
cout<<"\nEnter the elements: ";
for(i=0;i<n;i++)
cin>>a[i];
cout<<"\nENter elements to be searched: ";
cin>>val;
index=binary(a,n,val);
if(index>-1)
cout<<"\nEnter found at index: "<<index<<" and at position:
"<<index+1;
else
cout<<"Umsuccessful search ";
getch();
return 0;
}
int binary(int m[],int j,int k)
{
int low,mid,high,flag=0,i;
low=0;
high=j-1;
while(low<=high && flag==0)
{
mid=(low+high)/2;
if(k==m[mid])
{
flag=mid;
return flag;
}
else if(k<m[mid])

high= mid-1;

1
else
low=mid+1;
}
return-1;
}

You might also like