Sunday, May 5, 2013

Linear Search and Binary Search in C Language


Write C programs that use both recursive and non recursive functions to perform the following searching operations
for a Key value in a given list of integers : i) Linear search ii) Binary search
/*Write a C program Linear Search Using Non-Recursive Functions*/
#include<stdio.h>
#include<conio.h>
main()
{
    int a[100],i,n,ele,loc=-1;
    clrscr();
    printf("Enter Size");
    scanf("%d",&n);
    printf("Enter %d elements",n);
    for(i=0;i<n;i++)
    scanf("%d",&a[i]);
    printf("The array elements");
    for(i=0;i<n;i++)
    printf("%4d",a[i]);
    printf("\nEnter element to search");
    scanf("%d",&ele);
    for(i=0;i<=n-1;i++)
    {
      if(ele==a[i])
      {
        loc=i;
        break;
      }
    }
    if(loc>=0)
    printf("\nThe element %d found at %d location",ele,loc+1);
    else
    printf("\nThe element %d is not found",ele);
    getch();
}
int lin_search(int x[100],int n,int ele)
{
    if(n<=0)
    return -1;
    if(x[n]==ele)
    return n;
    else
    return lin_search(x,n-1,ele);
}

Output:
Enter Size5
Enter 5 elements12
30
25
4
85
The array elements  12  30  25   4  85
Enter element to search25

The element 25 found at 3 location

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More