Home » Sometech » WAP to search an item in a sorted array using binary search.

WAP to search an item in a sorted array using binary search.

#include<stdio.h>

#include<conio.h>

#define sf scanf

#define pf printf

#define size 20

void main()

{            

int n,i,a[size],item,flag=0,beg,end,mid;

clrscr();

pf(“Enter the number of elements=>”);

sf(“%d”,&n);

pf(“\nEnter the elements in ascending order”);

for(i=0;i<n;i++)

{

pf(“\nEnter element a[%d]=>”,i);

sf(“%d”,&a[i]);

}

pf(“\nThe original array elements are=>\n”);

for(i=0;i<n;i++)

pf(“\n%d”,a[i]);

pf(“\nEnter the element to search=>”);

sf(“%d”,&item);

beg=0;

end=n-1;

while(beg<=end)

{

mid=(beg+end)/2;

if(item==a[mid])

{

flag=1;

break;

}

if(item>a[mid])

beg=mid+1;

else

end=mid-1;

}

if(flag==1)

pf(“\n%d is found at position %d”,item,mid+1);

else

pf(“\n%d not found in the array”,item);

getch();

}

Advertisements

SoME Tech

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

%d bloggers like this: