C- Program for Binary Search
Posted on
Wednesday, 29 August 2012
by
Abc
C - Program for Binary Search
#include<stdio.h>
#include<conio.h>
void insertionsort(int a[],int n)
{
int i,j,temp;
for(i=1;i<n;i++)
temp=a[i];
for(j=n-1;j>=0 && a[j]<temp;j--)
a[j+1]=a[j];
a[j+1]=temp;
}
void main()
{
int i,j,key,n,a[100],flag,c;
clrscr();
printf("\nENTER THE NO. OF ELEMENTS:");
scanf("%d",&n);
printf("\nENTER THE ELEMENTS:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
insertionsort(a,n);
printf("\nENTER THE ELEMENT TO BE SEARCHED:");
scanf("%d",&key);
flag=0;
for(i=0,j=n-1;i<=j;)
{
c=(i+j)/2;
if(a[c]<key)
i=c+1;
if(a[c]>key)
j=c-1;
if(a[c]==key)
{
printf("ELEMENT FOUND AT POSITION:%d",c+1);
flag=1;
break;
}
}
if(flag==0)
printf("ELEMENT NOT FOUND!!!!");
getch();
}
This entry was posted in
Binary Search
.
Bookmark the
permalink.