Binary Search

Program:

#include<stdio.h>
int main()
{
    int numbers;
    printf("Enter the no.of.elements \n");
    scanf("%d",&numbers);
    int arr[numbers];
    int itr=0;
    for(itr=0;itr<numbers;itr++)
    {
        scanf("%d",&arr[itr]);
    }
    int search=0;
    printf("\n Enter the number to be searched : ");
    scanf("%d",&search);
    int first=0;
    int last=numbers-1;
    int middle = (first+last)/2;
    while(first<=last)
    {
        if(arr[middle]<search)

        {

            first = middle+1;
        }
        else if(arr[middle]==search)
        {
            printf("%d is present at %d position ",search,middle+1);
            break;
        }
       
        else
        {
            last = middle-1;
        }
        middle = (first+last)/2;
    }
    if(first>last)
    {
        printf("The value is not present ");
    }
    
}

OUTPUT:


Enter the no.of.elements                                                                                                                         
5                                                                                                                                                
98 176 543 654 777                                                                                                                               
                                                                                                                                                 
 Enter the number to be searched : 654                                                                                                           
654 is present at 4 position           


5                                                                                                                                              
6 7 8 9 99                                                                                                                                     
                                                                                                                                               
 Enter the number to be searched : 5                                                                                                           
The value is not present    




Comments

Popular posts from this blog

c++ program to print string along the diagonals of the matrix.

Kollywood Game

C program to print the following Pattern