Powered By Blogger

Friday, April 27, 2012

Program : 9


PROGRAM - 9

Write a program to perform the following:

ü  Linear Search.
ü  Binary Search.

Program for Linear search:

#include<stdio.h>
#include<conio.h>
main()
{
    int a[50],n,i,count=0,srch;
    clrscr();
    printf("enter the range");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
     printf("enter the %d element:",i);
     scanf("%d",&a[i]);
    }
    printf("enter the search element");
    scanf("%d",&srch);
    for(i=0;i<n;i++)
    {
     if(srch==a[i])
     {
        printf("element %d is present in %d position" 
                                            ,srch,i+1);
        count++;
     }
    }
    if (count==0)
    printf("element is not present");
    getch();
}

/*
INPUT:enter the range5
enter the 0 element:9
enter the 1 element:6
enter the 2 element:3
enter the 3 element:8
enter the 4 element:5
enter the search element6
OUTPUT:
element 6 is present in 1 position

*/

Program for Binary search:

#include<stdio.h>
#include<conio.h>
main()
{
    int n, a[50],i,lw,hgh,mid,srch,count=0;
    clrscr();
    printf("enter the range ");
    scanf("%d",&n);
    printf("enter the elements in ascending order \n");
    for(i=0;i<n;i++)
    {
       printf("enter the %d element:",i+1);
       scanf("%d",&a[i]);
    }
    printf("enter the element to be searched \n");
    scanf("%d",&srch);
    lw=0;
    hgh=n;
    for(i=0;lw<=hgh;i++)
    {
       mid=(hgh+lw)/2;
       if(a[mid]==srch)
       {
       printf("the number is present in %d position"
                                             ,mid+1);
       count++;
       break;
       }
       if(a[mid]>srch)
       hgh=mid-1;
       else
       lw=mid+1;
    }
    if(count==0)
    printf("elenent is not present");
    getch();
}

/*
INPUT:enter the range 5
enter the elements in ascending order
enter the 1 element:5
enter the 2 element:10
enter the 3 element:15
enter the 4 element:20
enter the 5 element:25
enter the element to be searched 10
OUTPUT:
the number is present in 2 position */

No comments:

Post a Comment