#include <stdio.h>
// Define the product structure
typedef struct {
int id; // Product ID
char name[50]; // Product name (optional)
float price; // Product price (optional)
} Product;
// Binary search function to find product by ID
int binarySearch(Product products[], int size, int targetId) {
int left = 0;
int right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // Find the middle index
// Check if the target ID matches the middle element's ID
if (products[mid].id == targetId) {
return mid; // Return the index of the found product
}
// If target ID is smaller, ignore the right half
if (products[mid].id > targetId) {
right = mid - 1;
}
// If target ID is larger, ignore the left half
else {
left = mid + 1;
}
}
return -1; // Return -1 if the product ID is not found
}
int main() {
// Example array of products (already sorted by product ID)
Product products[] = {
{101, "Product A", 10.99},
{102, "Product B", 15.49},
{103, "Product C", 7.99},
{104, "Product D", 23.99},
{105, "Product E", 12.49}
};
int size = sizeof(products) / sizeof(products[0]); // Calculate the number of products
int targetId = 103; // Example ID to search for
int index = binarySearch(products, size, targetId);
if (index != -1) {
printf("Product found: ID = %d, Name = %s, Price = %.2f\n", products[index].id, products[index].name, products[index].price);
} else {
printf("Product with ID %d not found.\n", targetId
); }
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CgovLyBEZWZpbmUgdGhlIHByb2R1Y3Qgc3RydWN0dXJlCnR5cGVkZWYgc3RydWN0IHsKICAgIGludCBpZDsgICAgICAgICAvLyBQcm9kdWN0IElECiAgICBjaGFyIG5hbWVbNTBdOyAgLy8gUHJvZHVjdCBuYW1lIChvcHRpb25hbCkKICAgIGZsb2F0IHByaWNlOyAgICAvLyBQcm9kdWN0IHByaWNlIChvcHRpb25hbCkKfSBQcm9kdWN0OwoKLy8gQmluYXJ5IHNlYXJjaCBmdW5jdGlvbiB0byBmaW5kIHByb2R1Y3QgYnkgSUQKaW50IGJpbmFyeVNlYXJjaChQcm9kdWN0IHByb2R1Y3RzW10sIGludCBzaXplLCBpbnQgdGFyZ2V0SWQpIHsKICAgIGludCBsZWZ0ID0gMDsKICAgIGludCByaWdodCA9IHNpemUgLSAxOwogICAgCiAgICB3aGlsZS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