Friday, 29 August 2014

C Program for Binary Searching

This program performs searching in a sorted array using Binary Search algorithm. It takes the Number of values (max) in the list, the actual values in the list, and the value to be searched for as inputs. The program then searches for the value in the list using Binary Search method and  prints the location of the value, if it is found. Otherwise it displays an error message.

Pre-condition
The array used as input for the program should be sorted in ascending order. So the user has to enter the values in sorted order. This program does not sort the array. You can find program for sorting this site itself in the following sections.

C Program for Quick Sorting
C Program for Insertion Sorting
C Program for Bubble Sorting

Source code for Binary Search


/*
    Binary Search
    -------------
    Input:
        1. No. of values in the List
        2. Actual values in the list (in ascending order)
        3. The value to be searched for
    Output:
        1. If the "search value" is there in the list, location of the value
        2. If the value is there in the list, an error message.
*/


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

int main() {
    int i, first, last, middle, max, findme, list[100];

    clrscr();

    printf("Enter number of elements:");
    scanf("%d",&max);

    printf("Enter %d values:\n", max);

    for ( i = 0 ; i < max ; i++ )
        scanf("%d",&list[i]);

    printf("Enter value to be searched for:");
    scanf("%d",&findme);

    first = 0;
    last = max - 1;
    middle = (first+last)/2;

    while( first <= last )
    {
        if ( list[middle] < findme )
            first = middle + 1;
        else if ( list[middle] == findme )
        {
            printf("%d found at location %d.\n", findme, middle + 1);
            break;
        }
        else
            last = middle - 1;

        middle = (first + last)/2;
    }

    if ( first > last )
        printf("Not found! %d is not present in the list.\n", findme);

    getch();

    return 0;
}


Output



No comments:

Post a Comment