Binary search as the name suggests mainly concerns with the searching of elements which are already in sorted order.
For binary search we need few things to consider

Mid Point is find by the following way
mid=(high+low)/2
The high and low point needs to be the first and last position of the array.
This mid point is used for searching the element we search it by looking that either element is greater than mid point then search left side or if the element is greater then the mid point then search right side of the array
- We check the key or mid point of the array. If the key match found, we return its position, which is the index of the middle element of the array.
- If the key is less than the value of the middle element of the array, we repeat the above step on the sub-array on the left. If the key is greater than the value of the middle element of the array, we repeat the above step on the sub-array on the right.
- If the sub-array to be searched has zero item, it means the key cannot be found.
#include<stdio.h>
int main() {
int n, a[30], item, i, j, mid, top, bottom;
printf("Enter how many elements you want:\n");
scanf("%d", &n);
printf("Enter the %d elements in ascending order\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
printf("\nEnter the item to search\n");
scanf("%d", &item);
bottom = 1;
top = n;
do {
mid = (bottom + top) / 2;
if (item < a[mid])
top = mid - 1;
else if (item > a[mid])
bottom = mid + 1;
} while (item != a[mid] && bottom <= top);
if (item == a[mid]) {
printf("Binary search successfull!!\n");
printf("\n %d found in position: %d\n", item, mid + 1);
} else {
printf("\n Search failed\n %d not found\n", item);
}
return 0;
}
0 Comment(s)