C program on Binary Search Algorithm
This program uses the Binary search algorithm works as:- first sorts the strings entered and then searches the demanded string's address.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | #include<stdio.h> #include<conio.h> #include<string.h> int main() { int i,j,n,f,l,flag,mid; char str[20][100],temp[20]; char word[100]; clrscr(); puts("\t\nEnter the no. of string to be sorted:"); scanf("%d",&n); f=0,l=n; printf("Enter %d strings(must not be longer than 100 words)\nput a ENTER when one string ends:\n",n); for(i=0;i<=n;i++) gets(str[i]); //sorting the string for(i=0;i<=n;i++) { for(j=i+1;j<=n;j++) { if(strcmp(str[i],str[j])>0) { strcpy(temp,str[i]); strcpy(str[i],str[j]); strcpy(str[j],temp); } } } printf("The sorted string\n"); for(i=0;i<=n;i++) puts(str[i]); printf("\n\n\tEnter a word:"); gets(word); //searching a string while(f<=l) { mid=(f+l)/2; flag=strcmp(word,str[mid]); if(flag==0) { printf("String found at %d position",mid); break; } else if(flag>0) f=mid+1; else l=mid-1; } if(flag!=0) printf("strring NOT FOUND"); getch(); return 0; } |
OUTPUT: -
Comments
Post a Comment