Binary search in C

Binary search in C


Binary Search:

  • in computer science, binary search, also known as half-interval search, logarithmic search, or binarychop, is a search algorithm that finds the position of a target value within a sorted array.
  • It necessary that given data is sorted in ascending order or descending order.
  • below is the program of binary search for ascending ordered data.

PROGRAM :

#include <stdio.h>
#include <stdlib.h>

int main(int n,int a[10])
{
    int i,mid,key,ub,lb;
    printf("How many numbers you wants to enter=");
    scanf("%d",&n);

    lb=0;
    ub=n-1;

    printf("\n%d elements are=",n);

    for(i=0;i<n;i++){
            printf("\na[%d]=",i);
        scanf("%d",&a[i]);
    }
    printf("\nKey=",n);
    scanf("%d",&key);

    mid=(lb+ub)/2;

    while(a[mid]!=key && lb<=ub){
        if(key<a[mid]){
            ub=mid-1;
        }
        else{
            lb=mid+1;
        }
        mid=(lb+ub)/2;
    }

    if(a[mid]==key){
        printf("\nNumber has found");
        printf("\nPosition of number is %d",mid+1);
    }
    else{
        printf("Number hasn't found");
    }
    return 0;
}

OUTPUT:

How many numbers you wants to enter=5

5 elements are=
a[0]=12

a[1]=45

a[2]=56

a[3]=89

a[4]=90

Key=89

Number has found
Position of number is 4


Comments

Popular posts from this blog

Introduction to ChatGPT: Explain what ChatGPT is, how it works, and what it is used for.

Multi Level Inheritance In cpp

Hybrid Inheritance In cpp