Simple Binary Searching Program in C

Definition:

Binary search is a quickest search algorithm that finds the position of a target value within a sorted array

Also Called,

  • half-interval search
  • logarithmic search
  • binary chop

Simple Binary Searching Program 

/* Simple Binary Search Program Using Functions in C*/
/* Data Structure Programs,C Array Examples */

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

#define MAX_SIZE 5


int main() {
    int arr_search[MAX_SIZE], i,element;
	int f = 0, r =  MAX_SIZE, mid;
	
    printf("Simple Binary Search Example - Array\n");
    printf("\nEnter %d Elements for Searching : \n", MAX_SIZE);
    for (i = 0; i < MAX_SIZE; i++)
        scanf("%d", &arr_search[i]);

	printf("Enter Element to Search : ");
    scanf("%d", &element);
   

    while (f <= r) {
	  mid = (f+r)/2;

	  if (arr_search[mid] == element) {
         printf("\nSearch Element  : %d  : Found :  Position : %d.\n", element, mid+1);
         break;
	  }
      else if (arr_search[mid] < element)
         f = mid + 1;    
      else
         r = mid - 1;
   }
   
   if (f > r)
      printf("\nSearch Element : %d  : Not Found \n", element);
      
    getch();
}

Sample Output:

Simple Binary Search Example - Array

Enter 5 Elements for Searching :
12
34
56
78
90
Enter Element to Search : 78

Search Element  : 78  : Found :  Position : 4.