Showing posts with label SEARCHING. Show all posts
Showing posts with label SEARCHING. Show all posts

Saturday, 26 April 2014

Binary Search

PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
    int c, first, last, middle, n, f=0, search, array[100];
    clrscr();
    printf("\n\n\n Binary Search using Array \n\n\n");
    printf("Enter number of elements:\t");
    scanf("%d",&n);

    printf("Enter %d integers\n", n);
    for(c=0;c<n;c++)
    {
        scanf("%d",&array[c]);
    }
    printf("Enter value to find:\t");
    scanf("%d",&search);

    first = 0;
    last = n - 1;


    while( first <= last )
    {
        middle = (first+last)/2;
        if ( search < array[middle] )
        {
            last = middle - 1;
        }
        else if( search > array[middle] )
        {
            first= middle + 1;
        }
        else
        {
            printf("%d found at location %d.\n", search, middle+1);
            f=1;
            break;
        }
    }
    if ( f==0 )
    {
        printf("Not found! %d is not present in the list.\n", search);
    }
    getch();
}


OUTPUT:


Binary Search using Array

Enter number of elements:       5
Enter 5 integers
2
4
6
8
10
Enter value to find: 10
10 found at location 5.


 Binary Search using Array
 
Enter number of elements:       5
Enter 5 integers
1
3
5
7
9
Enter value to find: 8
Not found! 8 is not present in the list.

Linear Search


PROGRAM:

#include<stdio.h>
#include<conio.h>
void main()
{
    int a[10],i,n,key,f=0;
    clrscr();
    printf("\n\n LINEAR SEARCH \n\n");
    printf("Enter the array limit:\t");
    scanf("%d",&n);
    printf("Enter array elements:\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("Enter the element to be searched:\t");
    scanf("%d",&key);
    for(i=0;i<n;i++)
    {
        if(a[i]==key)
        {
            printf("Element found\n");
            f=1;
            break;
        }
    }
    if(f==0)
    {
        printf("Element not found\n");
    }
    getch();
}


OUTPUT:


LINEAR SEARCH

Enter the array limit:  5
Enter array elements:
1
3
5
7
9
Enter the element to be searched:       9
Element found



LINEAR SEARCH

Enter the array limit:  5
Enter array elements:
2
4
6
8
10
Enter the element to be searched:       9
Element not found