R
To use binarySearch, before you need to have an ordered Array.If you do this, you already change the result (but read to the end):java.util.Arrays.sort();
See this section of http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(java.lang.Object%5b%5d,%20java.lang.Object) :The array must be sorted into ascending order according to the natural ordering of its elements (as by the sort(Object[]) method) prior to making this call. If it is not sorted, the results are undefined.Translating:The array needs to be organized in increasing order according to the natural order of its elements (such as the sort(Object[]) method before making this call. If not organized, the results are indefinite.Notice how your test numbers were already ordered in the source, the result was expected. The countries in turn are not in natural order. If they were in order too, we probably wouldn't understand a potential problem.The solution, applied to your code, is simple... but read carefully what comes later.import java.util.Arrays;
public class ArraySimples {
public static void main(String[] args) {
String [] paises ={"Brasil", "Russia", "India", "China", "Argentina", "Paraguai"};
Arrays.sort(paises);
int posicao0 = Arrays.binarySearch(paises, "Brasil");
int posicao1 = Arrays.binarySearch(paises, "Russia");
int posicao2 = Arrays.binarySearch(paises, "India");
int posicao3 = Arrays.binarySearch(paises, "China");
int posicao4 = Arrays.binarySearch(paises, "Argentina");
int posicao5 = Arrays.binarySearch(paises, "Paraguai");
System.out.println("Brasil: " + posicao0);
System.out.println("Russia: " + posicao1);
System.out.println("India: " + posicao2);
System.out.println("China: " + posicao3);
System.out.println("Argentina: " + posicao4);
System.out.println("Paraguai: " + posicao5);
}
}
Working is different from being right Binary search only matters when they are several. Much more searches and at different times than what is in the question, as an entire list of countries that will be consulted numerous times in the code.Otherwise, it's much better to loop for.For you to better understand, we will use a more practical example:You have 600 books, mixed, and you just want one, "The Process" of Kafka.O sort + binarySearch it is you first organize ALL 600 in alphabetical order... and only after you finish ordering, you start looking. Take the middle, see if it's what you want, if it's not split the stack into two, look for one side, and so it goes, until it gets to the desired (being that by ordering the book has passed several times in your hand and vc did not catch). You realize this alternative isn't too smart?Much better is simply to look one by one in sequence, and when you find what you want, take and get out. End of story. That is, in the case of one or two searches only, the output even is to forget this binary search business and use a simple loop.