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

with function:
  1. #include <stdio.h>
  2. #include <string.h>

  3. int func(char str[100][100],int start,int end,char key[40])
  4. {
  5.     while(start <= end)
  6.     {
  7.         int mid = (start+end)/2;
  8.         if (strcmp(key, str[mid])==0)
  9.         {
  10.             printf("key found at the position %d\n", mid+1);
  11.             return 0;
  12.         }
  13.         else if
  14.                 (strcmp(key, str[mid])>0)
  15.         {
  16.             end = end;
  17.             start = mid+1;
  18.         }

  19.         else
  20.         {
  21.             start=start;
  22.             end = mid-1;
  23.         }
  24.     }
  25.     return -1;

  26. }
  27. int main()
  28. {
  29.     int i, n, start, end, mid;
  30.     char str[100][100], key[40];

  31.     printf("Please enter the number of string to be stored : ");
  32.     scanf("%d",&n);

  33.     printf("Enter the string in ascending order\n");

  34.     for(i=0; i<=n-1; i++)
  35.     {
  36.         scanf("%s", &str[i]);
  37.     }

  38.     printf("Enter the string to be searched : ");
  39.     scanf("%s", &key);

  40.     start = 0;
  41.     end = n-1;
  42.     if(func(str,start,end,key)==-1)
  43.         printf("Failed\n");
  44.     return 0;
  45. }


with recursion:
  1. #include <stdio.h>
  2. #include <string.h>

  3. int recursion(char str[100][100],int start,int end,char key[40])
  4. {
  5.     if(start>end)
  6.         return -1;
  7.     int mid = (start+end)/2;
  8.     if(strcmp(key, str[mid])==0)
  9.     {
  10.         printf("key found at the position %d\n", mid+1);
  11.         return 0;
  12.     }
  13.     else if(strcmp(key, str[mid])>0)
  14.     {
  15.         recursion(str,mid+1,end,key);
  16.     }
  17.     else
  18.     {
  19.         recursion(str,start,mid-1,key);
  20.     }

  21. }
  22. int main()
  23. {
  24.     int i, n, start, end, mid;
  25.     char str[100][100], key[40];

  26.     printf("Please enter the number of string to be stored : ");
  27.     scanf("%d",&n);

  28.     printf("Enter the string in ascending order\n");

  29.     for(i=0; i<=n-1; i++)
  30.     {
  31.         scanf("%s", &str[i]);
  32.     }

  33.     printf("Enter the string to be searched : ");
  34.     scanf("%s", &key);

  35.     start = 0;
  36.     end = n-1;
  37.     if(recursion(str,start,end,key)==-1)
  38.         printf("Failed\n");
  39.     return 0;
  40. }

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