Learn How Binary Search Method Works

Algorithm of Binary Search


Step 1: LOW = 0
HIGH = N-1
Step 2: Repeat up to Step4 while LOW ≤ HIGH
Step 3: MIDDLE = (LOW+HIGH)/2
Step 4: If X < A [MIDDLE] then
HIGH = MIDDLE – 1
Else if X > A [MIDDLE] then
LOW = MIDDLE + 1
Else
Write “Search is Successful”
Return 1
Step 5: Write “Search is Not Successful”
Return 0

     

Program of Binary Search


#include<stdio.h>
#include<conio.h>
#define N 5
void main()
{
int a[N]={10,20,30,40,50};
int x;
int binary(int *a,int x);
clrscr();
printf("Enter Element to Search:");
scanf("%d",&x);
binary(a,x);
getch();
}
int binary(int *a,int x)
{
int LOW=0;
int HIGH=N-1;
int MIDDLE;
while(LOW<=HIGH)
{
MIDDLE=(LOW+HIGH)/2;
if(x<a[MIDDLE])
{
HIGH=MIDDLE-1;
}
else if(x>a[MIDDLE])
{
LOW=MIDDLE+1;
}
else
{
printf("Element is Found");
return 1;
}
}
printf("Element is Not Found");
return 0;
}

Download Projects


Download Programs