C Program Binary Search


Following C program first ask to the user to enter "how many element he/she want to store in the array", then ask to enter the array element one by one". After storing the element in the array, program ask to enter the element which he/she want to search in the array whether the number/element is present or not in the given array. The searching technique used here is binary search which is fast technique:

#include<stdio.h>
#include<conio.h>
void main()
{
    clrscr();
    int n, i, array[50], search, first, last, middle;
    printf("Enter total number of elements :");
    scanf("%d",&n);
    printf("Enter %d number :", n);
    for (i=0; i<n; i++)
    {
        scanf("%d",&array[i]);
    }
    printf("Enter a number to find :");
    scanf("%d", &search);
    first = 0;
    last = n-1;
    middle = (first+last)/2;
    while (first <= last)
    {
        if(array[middle] < search)
        {
            first = middle + 1;

        }
        else if(array[middle] == search)
        {
            printf("%d found at location %d\n", search, middle+1);
            break;
        }
        else
        {
             last = middle - 1;
        }
        middle = (first + last)/2;
    }
    if(first > last)
    {
        printf("Not found! %d is not present in the list.",search);
    }
    getch();
}

Run1:


Run2: 

No comments:

Post a Comment

100 C Programs with Code and Output

Program 1: C Program To Read Two Numbers And Print The Sum Of Given Two Numbers. Program 2: C Program To Read Three Numbers And Prin...