Wednesday, 4 November 2015

Write A Program To Binary Search Using Dynamic Array

//program for binary search

#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
//By-Ghanendra Yadav
int *a,i,itm,s,j,flag=0,low,up,mid,temp;

cout<<"ENTER THE SIZE OF ARRAY : "<<endl;
cin>>s;

a=(int*)malloc(s*sizeof(int));

cout<<"ENTER THE NUMBER"<<endl;
for(i=0;i<s;i++)
{
cin>>a[i];
}

for(i=1;i<s;++i)
for(j=0;j<(s-1);++j)
if(a[j]>a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}

cout<<"ENTER THE NUMBER FOR SEARCHING : "<<endl;
cin>>itm;

low=0;
up=s-1;
mid=(low+up)/2;


if(itm<=a[mid])
for(i=0;i<=mid;i++)
{
if(a[i]==itm)
flag=1;
}


if(itm>a[mid])
for(i=mid;i<s;i++)
{
if(a[i]==itm)
flag=1;
}



if(flag==1)
cout<<" ITEM FOUND \n";
else
cout<<" ITEM NOT FOUND \n";
}

Output:-


No comments:
Write comments

Recommended Posts × +