DATA STRUCTURE & ALGORITHM USING C – LAB (2018407)
UNIT – 15
Develop a ‘C’ program to create
and implement BINARY SEARCHING
#include
<stdio.h>
void main()
{
int i, beg, end, middle, n, search, array[100];
printf("Enter the number of element\n");
scanf("%d",&n);
printf("Enter the %d numbers\n", n);
for (i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter number to be searched\n");
scanf("%d", &search);
beg = 0;
end = n - 1;
middle = (beg+end)/2;
while (beg <= end)
{
if (array[middle] < search)
beg = middle + 1;
else if (array[middle] == search)
{
printf("Search is successful.\n%d found at location %d.\n", search, middle+1);
break;
}
else
end = middle - 1;
middle = (beg + end)/2;
}
if (beg > end)
printf("Search is unsuccessful! %d isn't present in the list.\n", search);
getch();
}
void main()
{
int i, beg, end, middle, n, search, array[100];
printf("Enter the number of element\n");
scanf("%d",&n);
printf("Enter the %d numbers\n", n);
for (i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter number to be searched\n");
scanf("%d", &search);
beg = 0;
end = n - 1;
middle = (beg+end)/2;
while (beg <= end)
{
if (array[middle] < search)
beg = middle + 1;
else if (array[middle] == search)
{
printf("Search is successful.\n%d found at location %d.\n", search, middle+1);
break;
}
else
end = middle - 1;
middle = (beg + end)/2;
}
if (beg > end)
printf("Search is unsuccessful! %d isn't present in the list.\n", search);
getch();
}
0 Comments