EXPLORING CYBERSPACE…

Binary Search

January 25, 2009 · Leave a Comment

// PROGRAM TO BINARY SEARCH IN A LINEAR SORTED ARRAY  A[ ].

#include<stdio.h>
#include<conio.h>
#include<dos.h>
void main()
{
clrscr();
int A[25],i,n,BEG=1,END,MID,ITEM,pos;

printf(“nEnter the no of elements to be stored in the array (maximum ‘25′)n”);
scanf(“t%d”,&n);
printf(“nEnter the elements in array.(in ascending order) n”);
for(i=1;i<=n;i++)
scanf(“%d”,&A[i]);
printf(“nEnter the element to be searched out in the array”);
scanf(“%d”,&ITEM);

END=n;
MID=(BEG+END-1)/2;
while((A[MID]!=ITEM)&&(BEG<=END))
{
if(ITEM>A[MID])
BEG=MID+1;
else
END=MID-1;
MID=(BEG+END)/2;
}
if(A[MID]==ITEM)
{
pos=MID;
printf(“nSearch Successful::nnElement found at position %d”,pos);
}
else
printf(“nOops!! Element not found”);
delay(4000);
}
/*

OUTPUT==>

Enter the no of elements to be stored in the array (maximum ‘25′)
5
Enter the elements in array.(in ascending order)
1 2 3 4 5
Enter the element to be searched out in the array
4
Search Successful::

Element found at position 4
*/

Categories: Data Structures · Programming in C
Tagged:

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment