C Program For Binary Search Algorithm using Function
Learn How To Find an Element in 1-Dimensional Array using Binary Search in C Programming Language using Functions and Array. It is important that we should know How A For Loop Works before getting further with the C Program Code. The Binary Searching Algorithm cannot be implemented in Data Structures such as Linked Lists since direct access is not allowed in the Linked Lists. This is a king divide and conquer technique.
How Binary Search Algorithm Works?
It is important that the Elements entered in the Array must be in the Sorted Order otherwise the Binary Searching Algorithm would not work as expected. The search for the element starts by comparing the middle element first. If the element is found there, then the search stops, else the array is divided into two halves.
If the element to be searched is less than the middle element, the first half of the Array is selected to search. If the element to be searched is greater than the middle element, then the second half of the Array is selected to search. Again the middle element of the first half or the second half is compared. If the element is not found, the process of dividing the Array into two halves is continued till the element is not found.
The best case of Binary Searching is when the Element to be searched is present at the Middle position. The loop will, therefore, execute only once. The worst case would be when the Element is not present in the Array. The Run Time complexity of this Algorithm is O(log n).
Must Read: C Program For Binary Search using Recursion
C Program For Binary Search using Function
int BinarySearching(int arr, int max, int element)
int low = 0, high = max - 1, middle;
while(low <= high)
middle = (low + high) / 2;
if(element > arr[middle])
low = middle + 1;
else if(element < arr[middle])
high = middle - 1;
int count, element, limit, arr, position;
printf("Enter the Limit of Elements in Array:\t");
printf("Enter %d Elements in Array: \n", limit);
for(count = 0; count < limit; count++)
printf("Enter Element To Search:\t");
position = BinarySearching(arr, limit, element);
if(position == -1)
printf("Element %d Not Found\n", element);
printf("Element %d Found at Position %d\n", element, position + 1);
In case you get any Compilation Errors with this C Program To Search Array Element using Binary Search using Array and User Defined Functions or if you have any doubts about it, let us know about it in the Comment Section below.