Reputation: 13
I was asked to use binary search to find specific words in a file that we read.
The issue I do not understand is how to use a binary search when you are looking for words and not numbers.
Upvotes: 1
Views: 5692
Reputation: 464
Binary Search for string Implemented in C.
char *lineptr[MAXLINE] //Array of char pointers stores the address of string
int binsrch(char srch[],int low,int high)
{
int mid;
if(high>=low){
mid=(low+high)/2;
if(strcmp(srch,lineptr[mid])<0) //compare string stored in srch and lineptr[mid]
return binsrch(srch,low,mid-1,count);
else if(strncmp(srch,lineptr[mid],count)>0)
return binsrch(srch,mid+1,high,count);
else
return mid; // Found
}
return -1; //Not found
}
Upvotes: 0
Reputation: 2339
Think of looking up a word in the dictionary; this is an example of binary search.
For example, lets look up "eunoia":
This all works because the dictionary is well-ordered, we all agree that A is the 1st letter, B is the 2nd, etc. Another way to look at it is that the Alphabet is the same thing as the numbers [0 - 25] just with different names.
Upvotes: 1
Reputation: 25903
Binary search operates on sorted inputs. You can define an order also on words, not only on values.
For example the lexicographical order. In Java this is even implemented as the natural order of String
s. So you can do "text1".compareTo("text2")
and it returns the order.
A small illustration of binary search:
As you see, the only thing to decide in the algorithm is the order between two objects. For example, from the image, 7 < 14
and 7 > 6
. As said, you can also do this for String
s. Indeed for everything for which you define an order.
Actually many classes in Java (more than 150
) implement a natural order, they are listed under the interface Comparable
(documentation), they all provide a compareTo
method with a meaningful order.
Upvotes: 5