Please visit, subscribe and share 10 Minutes Lectures in Computer Science

## Binary search algorithm implementation using C program

### Program:

/* recursive binary search*/
#include<stdio.h>

int bsearch(int [ ],int, int, int); //function declaration

int main( )
{
int a[20], i, low_index, high_index;
int position, total_keys, key_to_find
printf("\nEnter the total number of values:");
scanf("%d", &total_keys);

for(i = 0; i < total_keys; i++)
{
printf("\nEnter the key elements %d  : ", i);
scanf("%d", &a[i]);
}
printf("\nEnter the key to search : ");
scanf("%d", &key_to_find);
low_index = 0;
high_index = n-1;
//the following line calls the function bsearch with parameters
position = bsearch(a, key_to_find, low_index, high_index);
if(position!=-1)
printf("Search successful, element found at position %d", position);
else
getch();
}

int bsearch(int a[ ], int k, int lb, int ub)
{
int mid;
while(ub >= lb) //repeat this loop while upper bound >= lower bound
{
mid=(lb+ub)/2; //finds new middle index in each iteration
if(k < a[mid]) //if the key_to_find is smaller than middle element of array,
ub = mid-1; //set the new upper bound as middle-1
else if(k > a[mid]) //if key_to_find is larger than middle
lb = mid+1; //set the new lower bound as middle+1
else if(k == a[mid]) //if key_to_find is equal to middle element
return(mid); //return the middle element as result
return (bsearch(a,k,lb,ub)); //if none of the above holds, call bsearch (recursive)
}
return -1; //if the key_to_find is not in the list, return -1 to tell ‘NOT FOUND’
}

**************

binary search program in C
binary search algorithm using recursive functions in C
binary search divide and conquer algorithm
binary search simple program in C

## Featured Content

### Multiple choice questions in Natural Language Processing Home

MCQ in Natural Language Processing, Quiz questions with answers in NLP, Top interview questions in NLP with answers Multiple Choice Que...

data recovery