C Program to find an Element using Binary Search

Binary Search is one of the most efficient searching algorithm due to its better time complexity with O(log N). The  working process of binary search is simple. 

1. All the elements must be in sorted order.

2. Find the MID element, compare the MID element with given Key.

3. If Key matched with MID, return.

4. If Key is less than the MID, go ahead with Left sub array and start from step 2.

5. If Key is Greater than the MID, go ahead with right sub array and start from step 2.

6. Repeat this process until you found a key or return with no key found.

//Program Name: BinarySearch.c #include<stdio.h>
int main()
{
    int c, first, last, middle, n, search, array[100];
    printf("Enter number of elements\n");
    scanf("%d",&n);
    printf("Enter %d integers\n", n);
    for ( c = 0 ; c < n ; c++ )
        scanf("%d",&array[c]);
    printf("Enter value to find\n");
    scanf("%d",&search);
    first = 0;
    last = n - 1;
    middle = (first+last)/2;
    while( first <= last )
    {
        if ( array[middle] < search )
            first = middle + 1;
        else if ( array[middle] == search )
        {
            printf("%d found at location %d.\n", search, 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", search);
    return 0;
}

Binary Search Program in C using Recursive and Non-Recursive Methods help you to solve the problem using both recursive and non recursive approaches.

Output for Binary Search:

1
2
3
4
5
6
7
8
9
10
11
12
Enter number of elements
6
Enter 6 integers
10
30
20
15
56
100
Enter value to find
33
Not found! 33 is not present in the list.

Leave a Reply

Your email address will not be published. Required fields are marked *