C source code for Searching algorithms

Jul 01, 2012 by Engineer's Vision


/* searching */

#include<stdio.h>
#include<conio.h>

int binsearch(int a[], int i, int j, int key);
int linsearch(int a[], int n, int key);
void main()
{
 clrscr();
 int a[30],n,i,key,result,op;
 do
 {
  printf("\n 1-linear search \n 2-binary search \n 3-exit");
  printf("\n enter your choice");
  scanf("%d",&op);
  switch(op)
  {
   case 1:
   printf("\n enter no of elements");
   scanf("%d",&n);
   printf("\n enter the array elements");
   for(i=0;i<n;i++)
   scanf("%d",&a[i]);
   printf("\n enter the no to be searched");
   scanf("%d",&key);
   result= linsearch(a,n,key);
   if (result==-1)
   printf("\n element not found");
   else printf("\n element found at the location %d",result+1);
   break;

   case 2:
   printf("\n enter no of elements");
   scanf("%d",&n);
   printf("\n enter the sorted array elements");
   for(i=0;i<n;i++)
   scanf("%d",&a[i]);
   printf("\n enter the no to be searched");
   scanf("%d",&key);
   result=binsearch(a,0,n-1,key);
   if (result==-1)
   printf("\n element not found");
   else printf("\n element found at the location %d",result+1);
   break;
  }
 }
while(op!=3);
getch();
}

int binsearch(int a[], int i, int j, int key)
{
 int c;
 if (i>j)
 return (-1);
 c= (i+j)/2;
 if (key==a[c])
 return(c);
 if (key>a[c])
 return(binsearch(a,c+1,j,key));
 return(binsearch(a,i,c-1,key));
}

int linsearch(int a[], int n, int key)
{
 int i;
 for(i=0;i<n;i++)
 {
  if (a[i]==key)
  return (i);
 }
 return(-1);
}

0 comments: