//WAP in C to take an array as an input and search a element using Binary Search Algorithm
#include<stdio.h>
int main()
{
int num, arr[30], item, i, j, mid, top, bottom; // required variables
printf("Enter how many elements you want:\n");
scanf("%d", &num); // input array size
printf("Enter the %d elements in ascending order\n", num);
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]); // input array elements in "ascending order"
}
printf("\nEnter the item to search\n");
scanf("%d", &item); // element to be searched
bottom = 1;
top = num;
/*initializing the value of mid, top and bottom according to the keyord to be searched */
do
{
mid = (bottom + top) / 2;
if (item < arr[mid])
top = mid - 1;
else if (item > arr[mid])
bottom = mid + 1;
}
/*Searching the array element in the required half of the array*/
while (item != arr[mid] && bottom <= top);
if (item == arr[mid]) // element must be found at middle position after each iteration
{
printf("Binary search successfull!!\n");
printf("\n %d found in position: %d\n", item, mid + 1);
}
else
{
printf("\n Search failed\n %d not found\n", item);
}
return 0;
getch(); // to hold the console screen
}
#include<stdio.h>
int main()
{
int num, arr[30], item, i, j, mid, top, bottom; // required variables
printf("Enter how many elements you want:\n");
scanf("%d", &num); // input array size
printf("Enter the %d elements in ascending order\n", num);
for (i = 0; i < num; i++)
{
scanf("%d", &arr[i]); // input array elements in "ascending order"
}
printf("\nEnter the item to search\n");
scanf("%d", &item); // element to be searched
bottom = 1;
top = num;
/*initializing the value of mid, top and bottom according to the keyord to be searched */
do
{
mid = (bottom + top) / 2;
if (item < arr[mid])
top = mid - 1;
else if (item > arr[mid])
bottom = mid + 1;
}
/*Searching the array element in the required half of the array*/
while (item != arr[mid] && bottom <= top);
if (item == arr[mid]) // element must be found at middle position after each iteration
{
printf("Binary search successfull!!\n");
printf("\n %d found in position: %d\n", item, mid + 1);
}
else
{
printf("\n Search failed\n %d not found\n", item);
}
return 0;
getch(); // to hold the console screen
}
No comments:
Post a Comment