Sunday, March 18, 2012

Linear and Binary Search

#include
#include

void Linear_Search()
{
int element,found_flag=0,i;
int array[20],no_of_elements;

printf("\n How many elements you want to insert in the array ?");
scanf("%d",&no_of_elements);

printf("\nEnter the elements in the array ");
for(i=0;i {
scanf("%d",&array[i]);
}

printf("\n Enter the element that you want to search ");
scanf("%d",&element);

for(i=0;i {
if(array[i]==element)
{
printf("\n Element Found !!!");
found_flag=1;
break;
}
}
if(found_flag==0)
printf("\nElement Not Found..");
}

void Binary_Search()
{
int element,found_flag=0,i,mid,low,high;
int array[20],no_of_elements;

printf("\n How many elements you want to insert in the array ?");
scanf("%d",&no_of_elements);

printf("\nEnter the elements in the array ");
for(i=0;i {
scanf("%d",&array[i]);
}

printf("\n Enter the element that you want to search ");
scanf("%d",&element);

high=no_of_elements-1;
low=0;

while(low<=high)
{
mid=(low+high)/2;
if(array[mid]==element)
{
printf("\nElement Found !!!");
found_flag=1;
break;
}
else
{
if(array[mid]>element)
{
high=mid-1;
}
else
{
low=mid+1;
}
}
}

if(found_flag==0)
printf("\nElement not found ");
}

void main()
{
int choice;

clrscr();


while(1)
{
printf("\n1.Linear Search");
printf("\n2.Binary Search");
printf("\n3.Exit");
printf("\nEnter your Choice ");
scanf("%d",&choice);
switch(choice)
{
case 1: Linear_Search();
break;
case 2: Binary_Search();
break;
case 3: exit(0);
}
}
}

No comments:

Post a Comment