Ans:->
What do you mean by Binary Search❓
Binary search is also known as Half interval search. It finds the positoin of the target value in a sorted array.
It compares the target value with the Mid element of the array. If they arer not equal then the half in which the target value cannot lie is eliminated and the search continues with the remainning half, again taking the Mid element and compairing it with the target value, and repeating this until the target value is not found and if the search ends with the remaining half being empty then the target value is not in the array.
The program to implement binary search in C language.
Program is as follows:--
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter value to find\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search)
{
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);
return 0;
}
OUTPUT:---
Enter number of elements
5
Enter 5 integers
45
78
96
15
18
Enter value to find
45
45 found at location 1.
0 Comments
If you want to give any suggestion regarding the post please feel free to Comment below-