Updated:13/08/2023 by Computer Hope
Go Back There are some important method that is very common :-- Binary search looks for a particular item by comparing the middle most item of the collection. If a match occurs, then the index of item is returned.
Binary search is a simple, common sense way to search through an ordered set of items. Questions, often referred to as queries or probes, are asked to find if the desired item is smaller or larger. If the question, hereafter called probe, is chosen from the middle of the sequence, ½ the possibilities are eliminated with each answer.
//Binary Search
#include<stdio.h>
#include<conio.h>
void main()
{
int x[10]={2,4,5,6,7,8,9,18,30,68};
int lb=0,ub=9,mid=4,sno;
clrscr();
printf("\nEnter searching no:");
scanf("%d",&sno);
while(lb<=ub)
{
if(x[mid]==sno)
{
printf("element fount and position=%d",mid+1);
return;
}
if(sno<x[mid])
ub=mid-1;
else
lb=mid+1;
mid=(lb+ub)/2;
}
printf("\n element not found");
getch();
}
In this article , binary search algorithm divides an array into smaller halves and eliminates one half of the search space at each iteration in order to search for an element in a sorted array.
Use cases of binary search : Use binary search to locate a letter in the alphabet A B C D E F G H I J K L M N O P Q R S T U V W X Y Z