Binary Search in C

For the binary search program in C Programming if the array values are not defined already it will ask the user first to enter the size of the array. Then the user will enter array elements one by one. After adding all the elements to array ask the user to enter the element to search in an array by using binary search.

It is required in binary search that all elements are in sorted form, otherwise, we should sort them first. If the user enters duplicate numbers, then there is no guarantee which element will be found in the binary search.

The program first checks whether the element present at middle, if not then the element  going to compare with middle value. If results greater then the element to search present in left sub-array otherwise present in right sub-array.

Program Example

Implementing binary search in C:

Following C programs illustrates implementation of binary search.

The output should be:

Element number of elements :
5
Enter total 5 integer values :
10
15
16
29
30
Enter the value to find :
29
29 found at index 3

LEAVE A REPLY

Please enter your comment!
Please enter your name here