For simplicity, let’s say that I have two sets of words, sorted into alphabetical order. One set starts at “aardvark” and ends at “melon”, and the other starts at “melon” and ends at “zebra”. The word “melon” appears in both sets.
If I were to take an input word, say “banana”, what would be a good (and efficient) way of determining which set of words it should belong to? Note: this isn’t a question about whether the word “banana” already exists in one set, but rather a question about how to determine which set the word should exist in.
If there is an algorithm that someone knows, great. If they can provide some version in Java, even better!
Edit: Should also point out, whilst my example only has 2 sets, I want the algorithm to work with n sets.
For two sets:
If
wordis your word (e.g."banana"):For
nsets:Place the dividing words into an
ArrayList<String>(call itdividers) in alphabetical order:Now you can use
Collections.binarySearch()to figure out which set the word belongs to:(Here, the sets are numbered from zero.)