Sponsored Ad
Showing posts with label C Inteview Questions. Show all posts
Showing posts with label C Inteview Questions. Show all posts

Saturday, May 8, 2010

What is Binary Search and How to implement in C

 

Binary search is search mythology in a sorted list. In this process first find the middle element of list and if it is equal to the middle element its done. other wise if number is greater than the middle number search in next half otherwise search in first half with same pattern(Find the middle  element and compare).

Here is Binary search implementation in C.

 

#include <stdio.h>

int binary_search(int array[], int value, int size)
{
    int found = 0;
    int high = size, low = 0, mid;

    mid = (high + low) / 2;

    printf("\n\nLooking for %d\n", value);

    while ((! found) && (high >= low))
    {
        printf("Low %d Mid %d High %d\n", low, mid, high);

        if (value == array[mid])
            found = 1;
        else if (value < array[mid])
            high = mid - 1;
        else
            low = mid + 1;

        mid = (high + low) / 2;
    }
    return((found) ? mid: -1);
}

void main(void)
{
    int array[100], i;

    for (i = 0; i < 100; i++)
        array[i] = i+20;

    printf("Result of search %d\n", binary_search(array, 44, 100));
    printf("Result of search %d\n", binary_search(array, 77, 100));
 
}

Sponsored Ad

Followers

Follow Us