Simple C Program to find Number Using Binary Search


    Using this program user can find number using binary search technique. It can only be used for sorted arrays. Core idea used in binary search is similar as searching phone number of person in telephone directory.  If process of searching finds a match of search key with list element value,search is successful else unsuccessful.

Recommended: Binary search using function recursion 

Program:


//C Program to find Number Using Binary Search by Slashmycode.com
#include<stdio.h>
#include<conio.h>
int main(){

    int a[10],i,n,m,c=0,l,u,mid;

    printf("Enter the size of an array: ");
    scanf("%d",&n);

    printf("Enter the elements in ascending order: ");
    for(i=0;i<n;i++){
         scanf("%d",&a[i]);
    }

    printf("Enter the number to be search: ");
    scanf("%d",&m);

    l=0,u=n-1;
    while(l<=u){
         mid=(l+u)/2;
         if(m==a[mid]){
             c=1;
             break;
         }
         else if(m<a[mid]){
             u=mid-1;
         }
         else
             l=mid+1;
    }
    if(c==0)
         printf("The number is not found.");
    else
         printf("The number is found at %d",mid+1);
//C Program to find Number Using Binary Search by Slashmycode.com
    return 0;

}



Output:

No comments:

Post a Comment

Feel free to ask us any question regarding this post