Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

How to implement binary search

I have a text file containing several words and pointers, like this:

String1 int1
String2 int2
String3 int3
.....

The String1, String2, String3.....are sorted in lexicographical order.

What I want to do is to search a word among those Strings, using binary search, and return the int value beside the matched String.

Could anybody give me some detailed help on this question? Thanks in advance.
[444 byte] By [WXY595] at [2007-11-11 8:01:25]
# 1 Re: How to implement binary search
do you know the details of the binary search algorithm? do you need help with that or do you need help implementing it in java?

Kind regards,
Noel
noelob at 2007-11-11 22:36:45 >
# 2 Re: How to implement binary search
First you have to implement a method which processes the content of the file.
The Scanner class will help immensely in that process - I would ask my implementation to tokenize the text using the new line symbol as the delimiter. The tokens will be put into a collection.

You can implement your own "search" of the String, or you can use the Scanner class's findInLine() method. If your current String contains the pattern, then use the nextInt() method to obtain the integer accompanying the String; then do next() to get the next token, and repeat.

There are some other methods of the Scanner class which can search across the entire file, ignoring delimiters.
nspils at 2007-11-11 22:37:46 >