Data Structures Practical 5
Question 1
Write a C program that performs binary search on a sorted array of strings. The program should: • Read a sorted list of strings from the user. • Ask the user for a target string to search for. • Use binary search to find the target string in the list. • Print the index of the target string if found, or a message indicating that the string is not found.
strbinsearch.c
C
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAX_STRINGS 100
#define MAX_LENGTH 50
void main()
{
int size, i, position, found=0;
char arr[MAX_STRINGS][MAX_LENGTH];
char target[MAX_LENGTH];
printf("Enter number of strings: ");
scanf("%d", &size);
printf("Enter %d strings in sorted order:\n", size);
for (i = 0; i < size; i++) {
scanf("%s", arr[i]);
}
printf("Enter the string to search for: ");
scanf("%s", target);
int beg = 0;
int end = size - 1;
while (beg <= end)
{
int mid = beg + (end - beg) / 2;
int res = strcmp(arr[mid], target);
if (res == 0)
{
position = mid;
found=1;
printf("String found at index %d.\n", position);
break;
}
if (res < 0)
beg = mid + 1;
else
end = mid - 1;
}
if (found==0)
printf("String not found in the list.\n");
getch();
}
Output
