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

Binary Search in C: String Comparison

Uploaded by

mayursarode820
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)
3 views3 pages

Binary Search in C: String Comparison

Uploaded by

mayursarode820
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

Practical No.

05
Practical Related Questions ANS
XIV 1) Ans
#include <stdio.h>
#include <string.h>
// Function to compare strings
int compareStrings(const char *str1, const char *str2) {
return strcmp(str1, str2);
}

// Function to perform binary search


int binarySearch(char *arr[], int low, int high, char *target) {
if (low > high) {
return -1;
}

int mid = (low + high) / 2;

if (compareStrings(arr[mid], target) == 0) {
return mid;
} else if (compareStrings(arr[mid], target) < 0) {
return binarySearch(arr, mid + 1, high, target);
} else {
return binarySearch(arr, low, mid - 1, target);
}
}

int main() {
int n;
printf("Enter the number of strings: ");
scanf("%d", &n);

char *strings[n];
printf("Enter %d sorted strings:\n", n);
for (int i = 0; i < n; i++) {
strings[i] = (char *)malloc(100 * sizeof(char));
scanf("%s", strings[i]);
}

char target[100];
printf("Enter the target string: ");
scanf("%s", target);

int result = binarySearch(strings, 0, n - 1, target);

if (result != -1) {
printf("Target string found at index %d\n", result);
} else {
printf("Target string not found\n");
}

// Free allocated memory


for (int i = 0; i < n; i++) {
free(strings[i]);
}

return 0;
}
Output:

You might also like