Write a program to search a character in a string using binary search

Write a program to search a character in a string using binary search.
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4. void main()
  5. {
  6.     int i, n, start, end, mid;
  7.     char str[100][100], key[40];
  8.    
  9.     printf("Please enter the number of string to be stored : ");
  10.     scanf("%d",&n);
  11.    
  12.     printf("Enter the string in ascending order\n");
  13.    
  14.     for(i=0; i<=n-1; i++) {
  15.         scanf("%s", &str[i]);
  16.     }
  17.    
  18.     printf("Enter the string to be searched : ");
  19.     scanf("%s", &key);
  20.    
  21.     start = 0;
  22.     end = n-1;
  23.     while(start <= end) {
  24.         mid = (start+end)/2;
  25.         if (strcmp(key, str[mid])==0)
  26.             {
  27.                 printf("key found at the position %d\n", mid+1);
  28.                 exit(0);
  29.             }
  30.         else if
  31.             (strcmp(key, str[mid])>0)
  32.             {
  33.                 end = end;
  34.                 start = mid+1;
  35.             }
  36.            
  37.         else {
  38.                 start=start;
  39.                 end = mid-1;
  40.             }
  41.     }
  42.     printf("Failed\n");
  43.  }

একটি মন্তব্য পোস্ট করুন