Thursday 3 October 2013

Binary Search using C

#include<stdio.h>
main()
{
int i,high,low,mid,size,search,array[20];
printf("\n(There is) none worthy of worship except Allah(Subhanahu wa ta'ala).Muhammad(Sallallahu alayhi wasallam) is Messenger of ALLAH(Subhanahu wa ta'ala).\n");
printf("\n Welcome to Binary Search program\n");
printf("\n How many elements you want to enter in this array\n");
scanf("%d",&size);
printf("\n Enter %d elements \n",size);
for(i=0;i<size;i++)
scanf("%d",&array[i]);
printf("\n Enter the element to be searched\n");
scanf("%d",&search);
high=size-1;
low=0;
mid=(high+low)/2;
while(low<=high)
{
if(array[mid]<search)
low=mid+1;
else if(array[mid]==search)
{
printf("\n Element(%d) found at position %d\n",search,mid+1);
break;
}
else
high=mid-1;
mid=(high+low)/2;
}
if(low>high)
printf("\n Element not found !!!\n");
}

No comments:

Post a Comment