0% found this document useful (0 votes)
7 views3 pages

43 (11B)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views3 pages

43 (11B)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Ex.

No: 11B IMPLEMENTATION OF BINARY SEARCH

Date:

AIM
To write a C program to perform Binary Search operation

ALGORITHM

1. Start the program.

2. Read the search element from the user.

3. Find the middle element in the sorted list.

4. Compare the search element with the middle element.

5. If both match, display "Element found!" and terminate.

6. If not, check if the search element is smaller or larger than the middle element.

7. If smaller, repeat for the left sublist; if larger, repeat for the right sublist.

8. Continue until the element is found or the sublist has only one element.

9. If not found, display "Element not found!" and terminate.

PROGRAM

#include <stdio.h>

void main()
{
int a[10], i, n, item, flag = 0, low, high, mid;

// Input size of the array and elements in ascending order


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]);
}
// Input the item to be searched
printf("Enter the number to be searched: ");
scanf("%d", &item);

// Initialize low and high for binary search


low = 0;
high = n - 1;

// Binary search algorithm


while (low <= high)
{
mid = (low + high) / 2;

// If item is found
if (item == a[mid])
{
flag = 1;
break;
}
// If item is smaller than the middle element, search in the left half
else if (item < a[mid])
{
high = mid - 1;
}
// If item is larger, search in the right half
else
{
low = mid + 1;
}
}

// Output the result


if (flag == 0)
{
printf("%d is not found\n", item);
}
else
{
printf("%d is at position %d\n", item, mid + 1);
}
}
OUTPUT

RESULT
Thus the program to perform binary search operation was executed successfully

You might also like