Tuesday, 3 September 2019

Search a particular string using binary search without recursion.


Search a particular string using binary search without recursion.



#include<stdio.h>
#include<string.h>

int main()
{

      setbuf(stdout, NULL);
      int i,n,low,high,mid;
      char a[50][50],key[20];
      printf("enter the number of names to be added\n");
      scanf("%d",&n);
      printf("enter the name in ascending order\n");
      for(i=0;i<=n-1;i++)
      {
            scanf("%s",&a[i]);
      }
      printf("\n");
      printf("enter the name to be searched\n");
      scanf("%s",&key);
      low=0;
      high=n-1;
      while(low<=high)
      {
            mid=(low+high)/2;
            if (strcmp(key,a[mid])==0)
            {
                  printf("key found at the position %d\n",mid+1);
                  exit(0);
            }
            else if(strcmp(key,a[mid])>0)
            {
                  low=mid+1;
            }
            else
            {
                  high=mid-1;
            }
      }
      printf("name not found\n");
}

Output:


enter the number of names to be added

5
enter the name in ascending order
Meenakshi
Anurag
Khwahish
Aarul
Sveni

enter the name to be searched
Sveni
key found at the position 5


1 comment:

  1. Best Bets No Deposit | Sports Toto 100
    If the bettor has an expired bonus, he will be awarded a free bet worth up to 오래된 토토 사이트 $10. However, if the bonus is A free bet worth up to $1000 will still have a good

    ReplyDelete

Stack and Queue as ADT in C++

Stack as ADT The functions associated with stack are: empty()  – Returns whether the stack is empty size()  – Returns the size o...