Binary Search in Array – C Program

Binary Search in Array – C Program

Write a C program to search an element in a given array using Binary Search.

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

void main()
{

 int a[20],i,max,min,mid,val,index,size;

 printf("Please, Enter total no of elements =");
scanf("%d", &size);

 printf("\nEnter enter values in ascending order\n");
 for(i=0;i<size;i++)
{
  printf("\nThe %d element = ", i+1);
  scanf("%d",&a[i]);
 }

 printf("\nEnter a value to be searched= ");
 scanf("%d",&val);

 max=9;
 min=0;
 index=0;
 while(min<=max)
 {
  mid=(max+min)/2;
  if(val==a[mid])
  {
   index=mid;
   break;
  }
  if(a[mid]>val)
   max=mid-1;
  else
   min=mid+1;
 }
 
 if(index !=0)
{
  printf("The element found at location = %d",index);
}
 else
{
  printf("The element not found in Array");
}
}

The output of binary search is:

Please, Enter total no of elements = 10
Enter enter values in ascending order

The 1 element= 10
The 2 element= 12
The 3 element= 26
The 4 element= 29
The 5 element= 31
The 6 element= 45
The 7 element= 66
The 8 element= 69
The 9 element= 82
The 10 element= 96

Enter a value to be searched = 66

The element found at location = 7

 

Leave a Reply

Your email address will not be published. Required fields are marked *