Search an element using binary search algorithm



Binary Search in C. A binary search is a simplistic algorithm intended for finding the location of an item stored in a sorted list. There are a few variations to the binary search in C program, such as testing for equality and less-than at each step of the algorithm.



Sample Program:


/*
Write a program to search an element through using binary search algorithm.
*/


#include <stdio.h>
#define SIZE 100

int binary_search(int arr[],int item, int low, int high);

main()
{
 int arr[SIZE],i, item, n;
 printf("Enter the number of elements : ");
 scanf("%d",&n);
 printf("Enter elements of the array(in sorted order) : \n");


 for(i=0; i<n; i++)
 scanf("%d",&arr[i]);
 printf("Enter the item to be searched : ");
 scanf("%d", &item);
 i = binary_search(arr,item,0,n-1);

if(i == -1)
printf("Not Present\n");

else
printf("Present at index %d\n", i);

}

int binary_search(int arr[],int item, int low, int up)
{
 int mid;

 if(up < low)
 return -1; /*not found*/
 mid = (low+up)/2;

 if(item > arr[mid])
 return binary_search(arr,item,mid+1,up); 
 /*Search in right portion, tail recursive call */

 else if(item < arr[mid])
 return binary_search(arr,item,low,mid-1); 
 /*Search in left portion, tail recursive call */

 else
 return mid; /*found*/


}


Post a Comment

0 Comments