Pages

Sunday

Binary Search C Program

  
#include<stdio.h> //header file
#include<process.h> //header file
#include<conio.h> //header file

int s;
void bin(int a[],int,int);

void main() {
  int l,u,i,a[10];
  clrscr();
  l=0;
  u=9;

  for(i=0;i<10;i++){
    printf("enter the %dth number",i);
    scanf("%d",&a[i]);
  }

  printf("enter a element that has to be searched");
  scanf("%d",&s);
  bin(a,l,u);
  getch();

} 
Binary Search Fucntion 

   
void bin(int a[],int l,int u){
  int m;
  m=(l+u)/2;
  if(s<a[m]){
    if(u>=l){
      u=m-1;
      bin(a,l,u);
    }else{
      printf("no. is not present in the list");
      getch();
     exit(0);
    }

  }else if(s>a[m]){
    if(l<=u){
      l=m+1;
      bin(a,l,u);
    }else{
      printf("the no. is not present in the list");
      getch();
      exit(0);
    }
  }else if(s==a[m]){
     printf("element exists at %d",m);
     getch();
     exit(0);
  }
} 

No comments:

Post a Comment