# A question on Binary Search

I compiled the following code:

``````#include<stdio.h>
int main()
{
int i,j,n;
char str[20][20],temp[20];
clrscr();
puts("Enter the no. of string(s) to be sorted");
scanf("%d",&n);
for(i=0;i<=n;i++)
gets(str[i]);
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 list:\n");
for(i=0;i<=n;i++)
puts(str[i]);
getch();
return 0;
}
``````

The question is to apply binary search to find the location of string (to be taken as an input from the keyboard). How should I do that?

Sort the array in which you have stored the strings and then use this:

``````// declarations like: char str[num+][100] : array for storing strings
// a: string to be searched
int low=0,high=num-1,pos=-1;
while(low<=high)
{
int mid = (low+high)/2;

if(strcmp(str[mid],a)==0)
{
pos=mid;
break;
}
else if(strcmp(str[mid],a) <0)// if the string at the middle is less than what we are searching
low=mid+1;
else
high=mid-1;  // middle string is greater, our string will be in left half
}``````

Please, put your code in proper blocks using indentation. Itâ€™s really tough to even read it!! No offence please, or you may like posting the ideone code.