Just working through the Java Collections lesson, and when I got to the
binarySearch example, I noticed that while it works, that is just a lucky
coincidence!
The mandatory sort before performing a binary search is missing - if Boston
is moved to index 3, the search fails and returns -1.
This code fixes the problem.
package binarysearching;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Set up testing data
String name[] = {
new String("Sang"),
new String("Shin"),
new String("Boston"),
new String("Passion"),
new String("Shin"),
};
// Create a List object
List l = Arrays.asList(name);
// Perform binary search
Collections.sort(l);
int position = Collections.binarySearch(l, "Boston");
System.out.println("Position of the searched item = " + position);
}
}
--
You received this message because you are subscribed to the Google Groups
"JPassion.com: Java Programming" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
Visit this group at http://groups.google.com/group/jpassion_java.
For more options, visit https://groups.google.com/groups/opt_out.