Binary Search Program using 1-D Array

Binary Search method is one of the most taught searching algorithm in any computer class. Here we are implementing binary search method on a sorted one dimensional array.

// program to implment binary search in single dimensional array
// here in this program we are supplying arrayy in ascending order
#include<iostream>
using namespace std;
int binary_search(int x[],int n,int data){
int first,last,mid,pos=0;
first =0;
last = n-1;
while(first<=last && pos==0){
mid = int((first+last)/2);
if(x[mid]==data)
pos=1;
else
if(x[mid]>data)
last = mid-1;
else
first = mid+1;
}
return pos;
}

int main(){
int x[10],i,data;
//input phase
for(i=0;i<10;i++)
{
cout<<“Enter x[“<<i+1<<“] Element :”;
cin>>x[i];
}
cout<<“\n Enter element that you want to search :”;
cin>>data;
//processing phase
int result = binary_search(x,10,data);
if(result==0)
cout<<“\n Your given element does not exist in this array”;
else
cout<<“\n Your element available in this array”;
return 0;
}

Author: rakesh kumar

cbsetoday.com is my online home, here I share all the information related to education, programming - and everything else that attract me. You can get in touch with me in these social sharing websites
Download File :

Leave a Reply