Hello, Today I am sharing how to implement Binary Search in C Programming
language. Here is the basic algorithm for binary search:
C program for binary search :
#include<stdio.h>
int main(){
  int a[8];
  int i,x,first,last,mid;
	printf("\nEnter 8 sorted elements like 
               [2 4 7 9 12 13 16 20]");
	for(i=0;i<8;i++)
	{
		scanf("%d",&a[i]);
	}
	printf("\nYou entered following numbers:");
	for(i=0;i<8;i++){
		printf(" %d",a[i]);
	}
	printf("\nEnter the number you want to search: ");
	scanf("%d",&x);
	first=0,last=n-1;
	while(first<=last){
      mid=(first+last)/2;
	  if(x==a[mid]){
		printf("\nThe number is found at %d", mid);
        return 0;
      }
      else if(x<a[mid]){
		last=mid-1;
      }
      else
		first=mid+1;
	}
    printf("\nThe number is not in the list");
	return 0;
}
I hope you this post is helpful for you. Thanks for reading.

 
 
Dont SPAM