Write c program for searching an element from the given array using Binary search

#include<stdio.h>
#include<conio.h>

//To define functions
void binary_search(int [], int, int, int);

void main()
{
    int no, n, i;
    int a[25];
    printf("How many elements you want in array(Sorted array): ");
    scanf("%d", &n);
    printf("Enter elements:\n");
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("\n");
    printf("Enter no to search\n");
    scanf("%d", &no);
    binary_search(a, 0, n, no);
    getch();
}

//To  searching an element 
void binary_search(int a[], int lb, int ub, int no)
{
    int mid;
    if (lb>ub)
    {
        printf("Element not found\n");
        return;
    }
    mid=(lb+ub)/2;
    if (a[mid]==no)
    {
        printf("Element %d found at position %d\n",no,mid+1);
    }
    else if (a[mid] > no)
    {
        binary_search(a, lb, mid - 1, no);
    }
    else if (a[mid] < no)
    {
        binary_search(a, mid + 1, ub, no);
    }
}

0 Comments