Binary Search Program in C

Binary search program in c using function and without using function is given below with the output.

About Binary Search

Binary search is a divide and conquer search algorithm used primarily to find out the position of a specified value within an array. It should be noted that, for binary search to operate on arrays, the array must be sorted in either ascending or descending order. Since, binary search requires arrays to be sorted, therefore, this is also the disadvantage of binary search technique.

However, the main advantage of binary search is higher performance. Since, a binary search halves the number of items to check with each successive iteration, so searching for an item in the array, takes lesser time as not every element is checked.

Binary Search Program in C Without Using Function

#include<stdio.h>

main()
{
    int a[100],n,x,i,beg,end,mid,flag=0;

    printf("Enter size of arrayn");
    scanf("%d",&n);
    printf("Please enter array elements in ascending ordern");
    for(i=0; i<n; i++)
    {
        printf("Enter elementn");
        scanf("%d",&a[i]);
    }
    printf("Enter element to be searchn");
    scanf("%d",&x);

    beg=0;
    end=n-1;
    while(beg<=end)
    {
        mid=(beg+end)/2;
        if(a[mid]==x)
        {
            printf("Element found at %d position",mid + 1);
            flag=1;
            break;
        }
        if(a[mid]>x)
            end=mid-1;
        else
            beg=mid+1;
    }
    if(!flag)
        printf("No such element is foundn");

    getch();
    return 0;
}

Output

Binary Search Program in C Using Function

#include<stdio.h>

int binary_search(int *a,int n,int x);

main()
{
    int a[100],n,x,i,flag;
    printf("Enter size of arrayn");
    scanf("%d",&n);
    printf("Please enter array elements in ascending ordern");
    for(i=0; i<n; i++)
    {
        printf("Enter elementn");
        scanf("%d",&a[i]);
    }
    printf("Enter element to be searchn");
    scanf("%d",&x);

    flag=binary_search(a,n,x);

    if(flag)
        printf("Element found at %d position",flag + 1);

    else
        printf("No such element is foundn");

    getch();
    return 0;
}
int binary_search(int *a,int n,int x)
{
    int beg,end,mid;
    beg=0;
    end=n-1;
    while(beg<=end)
    {
        mid=(beg+end)/2;
        if(*(a+mid)==x)
        {
            return mid;
            break;
        }
        if(*(a+mid)>x)
            end=mid-1;
        else
            beg=mid+1;
    }
    return 0;
}

Output

3 Responses

  1. ramya
    ramya December 4, 2012 at 6:42 pm | | Reply

    i need count the number of words in a string ! !

  2. Asif Hazarika
    Asif Hazarika May 27, 2014 at 6:29 am | | Reply

    Great way to learn programming in C

  3. Asif Hazarika
    Asif Hazarika May 27, 2014 at 6:30 am | | Reply

    Corrected email addr

Please comment with your real name using good manners.

Leave a Reply