Binary search implementation in C
Searching is a process of finding an element from a group of elements. Binary search is one of the efficient search algorithms. Let us implement it in C language.
Implementation:
- This algorithm follows a method as follows.
- First, find the middle element.
- Check the element to be searched with middle element.
- If it is small, search the element in the left child of the array.
- If it is large, go for right side.
- Repeat this process to find the exact position.
C Code:
#include <stdio.h>
int binarySearch(int a[], int n, int key) {
int low = 0, high
= n - 1;
while (low <=
high) {
int mid = (low
+ high) / 2;
if (a[mid] ==
key)
return
mid; // yes ,it is Found
else if
(a[mid] < key)
low = mid
+ 1; // Search in right half
else
high = mid
- 1; // Search in left half
}
return -1; // It
is Not found
}
int main() {
int a[10];
int n,key,i;
printf("Enter
the number of elements:");
scanf("%d",&n);
printf("Enter
the elements");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter
the key value to search using Binary Search");
scanf("%d",&key);
int s =
binarySearch(a, n, key);
if (s != -1)
printf("Element is found at index %d\n",s);
else
printf("Sorry, the element is not found\n");
return 0;
}
Output1: Element is found
Compile and run the program to get the output.
Enter the number of elements:5
Enter the elements34 45 56 67 78
Enter the key value to search using Binary Search 45
Element is found at index 1
Output2: Element is not found
Enter the number of elements:6
Enter the elements45 56 67 78 89 91
Enter the key value to search using Binary Search 23
Sorry, the element is not found
Yes. That’s all. two different outputs are shown here to
clear explanation. Hope, you found useful in this coding. Keep coding!!!
Comments
Post a Comment