Specification: 5© C Program Program To Impliment Binary Search Algorithm
Specification: 5© C Program Program To Impliment Binary Search Algorithm
SPECIFICATION:
5 C Program Program to impliment binary search
ALGORITHM:
Step 1: Start
Step 2: Declare integer variables a[10] ,I ,n, m, c=0, l, u, mid
Step 3: Read n
Step 4: i is initialized as 0and in steps of 1 do the condition i<n is checked until the it fails
Step 4.1 : read a[i]
Step 5: Read m
Step 6: Initialize l=0 , u=n-1
Step 7: while(l<=u)
Do
Step 7.1: mid(l+u)/2
Step 7.2: check m== a[mid] if condition true then
Step 7.2.1: c1
Step 7.2.2: Stop
otherwise
step 7.3: check m<a[mid] if condition true then
Step 7.3.1: umid-1
otherwise
step 7.4: i mid+1
done
Step 8: check c==0 if condition is true
Step 8.1 : display he number is not found. Otherwise display number is found
Step 9: Stop
Department of Computer Science & Engg
FLOWCHART:
START
read n
false
for i=0 in steps of 1 do where i<n
true
read a[i]
Read m
l0
un-1
false
while l<=u
true
mid(l+u)/2
false
C==0
false
true
The number is
found
m==a
[mid]
false
true
c 1
m<a[mid]
I mid+1
u mid-1
true
stop
The number is
not found
PROGRAM
/* C Program to implement binary search */
Program name:
/* Done By : C-Faculty
#include<stdio.h>
int main()
{
int a[10],i,n,m,c=0,l,u,mid;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements in ascending order: ");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
l=0,u=n-1;
while(l<=u){
mid=(l+u)/2;
if(m==a[mid])
{
c=1;
break;
}
else if(m<a[mid]){
Department of Computer Science & Engg
// wk5c.c
Dated: 15/10/2013*/
u=mid-1;
}
else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");
return 0;
}
PROCEDURE FOR EXECUTING THE PROGRAM:
Step 1: After typing the program, press ESC button+shift+: and then type wq(to save the
program and quit)
Step 2: Now compile the program by using the following command
cc wk5c.c lcurses -lm
Step 3: Now go for running the program by using the command
./a.out
--xXx--