Quantcast
Channel: The Crazy Programmer
Viewing all articles
Browse latest Browse all 761

Binary Search in C

$
0
0

Here you will get program for binary search in C.

Binary search algorithm can be applied on a sorted array to search an element. Search begins with comparing middle element of array to target element. If both are equal then position of element is returned. If target element is less than middle element of array then upper half of array is discarded and again search continued by dividing the lower half. If target element is greater than middle element then lower half is discarded and search is continued in upper half.

Binary Search in C

Worst Case Time Complexity: O(log n)

Best Case Time Complexity: O(1)

Also Read: Linear Search in C

Program for Binary Search in C

Below program shows the implementation of binary search algorithm in C.

#include<stdio.h>

int main()
{
    int arr[50],i,n,x,flag=0,first,last,mid;

    printf("Enter size of array:");
    scanf("%d",&n);
    printf("\nEnter array element(ascending order)\n");

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

    printf("\nEnter the element to search:");
    scanf("%d",&x);

    first=0;
    last=n-1;

    while(first<=last)
    {
        mid=(first+last)/2;

        if(x==arr[mid]){
            flag=1;
            break;
        }
        else
            if(x>arr[mid])
                first=mid+1;
            else
                last=mid-1;
    }

    if(flag==1)
        printf("\nElement found at position %d",mid+1);
    else
        printf("\nElement not found");

    return 0;
}

Output

Enter size of array:6

Enter array element(ascending order)
20 27 40 50 58 99

Enter the element to search:27

Element found at position 2

The post Binary Search in C appeared first on The Crazy Programmer.


Viewing all articles
Browse latest Browse all 761

Trending Articles