Program 09: Find book availability using Binary Search.
Problem Statement:: A college library has a digital bookshelf system where each book is assigned a unique Book ID. The bookshelf is organized in ascending order of Book IDs. Develop a C Program to quickly find whether a book with a specific Book ID is available in the shelf using the binary search algorithm.
Problem Description:
Input: Total number of books (n), a sorted list of Book IDs, and the specific Book ID (key) to be searched.
Output: A message indicating whether the book is "Available" or "Not available".
Constraints: The number of books must be greater than zero; the input Book IDs must be provided in ascending order; IDs are assumed to be valid integers.
Method: Utilize the Binary Search algorithm to efficiently locate the key within the sorted array.
Pgm Logic:
Start.
Input the total number of books n.
Input n Book IDs into an array books[] in ascending order.
Input the key ID to be searched.
Initialize low = 0, high = n-1, and found = 0.
Repeat while low <= high:
Calculate mid = (low + high) / 2.
If books[mid] == key, set found = 1 and exit the loop.
Else if books[mid] < key, set low = mid + 1.
Else, set high = mid - 1.
If found == 1, print "Book is available".
Else, print "Book is not available".
Stop.
Program Code:
// Purpose: To find if a specific Book ID is available in a sorted digital bookshelf using Binary Search.
#include <stdio.h>
int main()
{
int n, i, key, low, high, mid, found = 0;
printf("Enter number of books: ");
scanf("%d", &n);
int books[n];
printf("Enter %d Book IDs in ascending order:\n", n);
for(i = 0; i < n; i++)
scanf("%d", &books[i]);
printf("Enter Book ID to search: ");
scanf("%d", &key);
low = 0;
high = n - 1;
while(low <= high)
{
mid = (low + high) / 2;
if(books[mid] == key)
{
found = 1;
break;
}
else if(books[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
if(found)
printf("Book is available.\n");
else
printf("Book is not available.\n");
return 0;
}
Output:
Enter number of books: 4
Enter 4 Book IDs in ascending order: 101 105 110 115
Enter Book ID to search: 110
Book is available.
RESULT: Thus the program has been executed and the output was verified.
Remarks: This program was compiled and run in the Code::Blocks IDE. Note that the Binary Search algorithm requires the input array to be sorted to function correctly.
Program Explanation: The program divides the search area in half during each iteration. By comparing the middle element to the key, it determines if the target is in the lower or upper half, drastically reducing the number of comparisons compared to a linear search.
For all 2026 published C Lab Program posts Index page: click here:
For all 2026 published articles list:click here:
…till the next post, bye-bye & take care