Menu

WAP in C to Perform Search Operation Using:-


a.     Linear Search(Non Recusrion and Recursion)
b.     Binary Search(Non Recusion and Recursion)
Solution:
a.Linear Search
Non Recursion
#include<stdio.h>
#include<conio.h>
void main()
{
int i,a[10],e,flag=1,n;
clrscr();
printf("\n enter the no. of elements which you want to enter:- ");
scanf("%d",&n);
printf("\n Enter the elements of an array:- ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n Searching Using linear search  ");
printf("\n enter the element which you want to search:-  ");
scanf("%d",&e);
for(i=0;i<n;i++)
{
if(a[i]==e)
{
printf("\n item found at %d location",i);
flag=0;
break;
}
else
flag=1;
}
if(flag==1)
printf("\n item not found ");
getch();

}

Recursion:
#include<stdio.h>
#include<conio.h>
int linear(int a[10],int l,int el);
void main()
{
 int i,e,a[10],n;
 clrscr();
 printf("\n enter the no. of elements which you want to enter:- ");
 scanf("%d",&n);
 printf("\n Enter the elements of an array:- ");
 for(i=0;i<n;i++)
 scanf("%d",&a[i]);
 printf("\n Searching Using linear search  ");
 printf("\n enter the element which you want to search:-  ");
 scanf("%d",&e);
 e=linear(a,n,e);
 if(e==1)
  printf("\n item not found ");
 else
  printf("\n item found at %d",e);
 getch();
}
int linear(int a[10],int l,int el)
{
 int i,flag=1;
 for(i=0;i<l;i++)
 if(a[i]==el)
 {
   flag=i;
 }
 if(flag==1)
  return 1;
 else
  return flag;
}          

b.Binary Search
Non Recursion
#include<stdio.h>
#include<conio.h>
void main()
{
 int a[10],val,n,low,high,mid,i;
 clrscr();
 printf("\n how many elements do you want to insert:-  ");
 scanf("%d",&n);
 printf("\n Enter the elements in sorted order:-  ");
 for(i=0;i<n;i++)
  scanf("%d",&a[i]);
 low=0;
 high=n-1;
 mid=(low+high)/2;
 printf("\n enter the element which you want to search:-  ");
 scanf("%d",&val);
 while(high>=low)
 {
  if(val==a[mid])
  {
  printf("\n value found at %d position",mid);
   break;
  }
  else if(val<a[mid])
   high=mid-1;
  else
   low=mid+1;
  if(val>high)
  {
   printf("\n search unsuccessful");
   break;
  }
  mid=(low+high)/2;
 }
 getch();

}

Recursion
#include<stdio.h>
#include<conio.h>
void binary(int b[10],int v,int l);
void main()
{
 int a[10],val,n,i;
 clrscr();
 printf("\n enter how many elements do you want to enter:-  ");
 scanf("%d",&n);
 printf("\n enter the elements in sorted order:-  ");
 for(i=0;i<n;i++)
  scanf("%d",&a[i]);
 printf("\n enter the element which do you want to search:-  ");
 scanf("%d",&val);
 binary(a,val,n);
 getch();
}
void binary(int b[10],int v,int l)
{
 int low,mid,high;
 low=0;
 high=l-1;
 mid=(low+high)/2;
 while(high>=low)
 {
  if(v==b[mid])
  {
   printf("\n value found at %d position ",mid);
   break;
  }
  else if(v<b[mid])
   high=mid-1;
  else
   low=mid+1;
  if(v>high)
  {
   printf("\n search unsuccessful ");
   break;
  }
  mid=(low+high)/2;
 }
}

No comments:

Post a Comment