TAB

C-Program For Binary Search


C-Program For Binary Search
#include<stdio.h>
int main(){

    int a[10],i,n,e,var=0,low,high,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 Element to be searched: ");
    scanf("%d",&e);

    low=0,high=n-1;
    while(low<=high){
         mid=(low+high)/2;
         if(e==a[mid]){
             var=1;
             break;
         }
         else if(e<a[mid]){
             high=mid-1;
         }
         else
             low=mid+1;
    }
    if(var==0)
         printf("The Element is not found.");
    else
         printf("The Element is found.");

    return 0;
}

output:
Enter the size of an array: 6
Enter the elements in ascending order: 1 3 6 8 9 13
Enter the Element to be searched: 9
The Element is found.

No comments:

Post a Comment

Related Posts

Related Posts Plugin for WordPress, Blogger...