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 :

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

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 shubhanshu
2 test
3 C program for Breadth First Search.
4 C program for Depth First Search(DFS).
5 C for circular queue using linked list.