C program for binary Search.

Posted by Mangesh on March 20, 2018

/* Binary Search */

Description :

Binary search finds the position of a target value within a sorted array. We need array to be sort in order to apply binary search algorithm.

Logic :

In binary we compare the target element with the middle element, if both the elements are equal we return the result else if the middle element is smallest then target element we simply move towards the upper array, else if the middle element is largest then target element we move towards lower array. We follows this process till we find the element or at max log(n) times.

Program :

#include<stdio.h>
#include<conio.h>
void main()
{
  int start=0,mid,end,n,i,key;
  int arr[20];
  printf("\n\nEnter total number of elemnt in array : ");
  scanf("%d",&n);
  end = n-1;
  for(i=0;i<n;i++)
  {
    printf("Enter %d element : ",i);
    scanf("%d",&arr[i]);
  }
  printf("Enter the number to search : ");
  scanf("%d",&key);
  while(end >= start)
  {
    mid = (end+start)/2;
    if(arr[mid]== key)
       break;
    else if(arr[mid]<key)
      start = mid+1;
   else
     end = mid - 1;
  }
  if(arr[mid] == key)
     printf("Found at %d.",mid);
  else
    printf("Element not found.");
  getch();
}

Output :

C program for binary search Tested in Turbo C 3.2

Written with from Mangesh.

Related Post
1 C program for binary Search.
Latest Post
1 C program to implement Queue using linked list.
2 C program for binary search tree (BST).
3 C program to search an element in linked list.
4 C program for postorder traversal in binary tree.
5 C program for preorder traversal in binary tree.