Incorrect value in vector when binary search

Asked

Viewed 180 times

5

import java.util.Arrays;

/**
 * @author Vinicius
 *
 */
public class Vetor04 {
    /**
     * @param args
     */
    public static void main(String[] args) {
        int vet[] = {3, 7, 6, 1, 9, 4, 5};
        int s = Arrays.binarySearch(vet, 3);
        System.out.println(s);

    }

}

I’m trying to do vector index 3 vet appear but instead of printing 1 print -5, what is the reason for this?

  • Binary research has the ordering principle ... I think this method follows this.

  • All knowledge is valid, and you can see that the solutions can fit within a problem. All experiences are valid and I answered according to the question. If your question was about that method was answered and explained according to your question and the reasons.

2 answers

8

Although you want to use the method Arrays.binarySearch() to find a value in a array not classified (the correct term, because ordered the array is, it has an order, data entry order) and this method should not be applied. It was created to handle when you have already sorted data.

The solution of classifying the array to then make the binary search work, but it’s not right:

Fiat 147 todo detonado andando pelas ruas

It is only worth using a binary search with a collection of data that is guaranteed to be classified since the sorting effort is at least (and would be in an ideal condition that in practice does not happen) equal to doing a linear search, it is usually much higher. And in practice the classification algorithm is less efficient even in detail than the linear search in most situations because it is bad of reference location. To be more accurate the linear search arrive be better even in arrays small that are already classified.

So if you want to learn to apply the algorithm correctly, you shouldn’t apply it in this case. You’re learning to use the mechanism, but you’re also learning to use it the wrong way and it can haunt you forever. And we’re not talking about a small difference when the volumes are bigger, you can create very tragic situations if you keep doing so because you learned that solves in Stack Overflow.

Doing linear search produces the same result much more efficiently. Although you don’t need this efficiency in an exercise the goal is not even this, is to teach right to apply well in the next times:

class Main {
    public static void main (String[] args) {
        int vet[] = { 3, 7, 6, 1, 9, 4, 5 };
        for (int i = 0; i < vet.length; i++) if (vet[i] == 3) {System.out.println(i); break; }
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

There are several other ways to do this.

And note that it returns the real position, you may want it or not. The ready function returns the insertion position.

The worst case of this algorithm is O(N), but it may be O(1) in the best case. The best case of the binary search that needs to classify the data is O(N)+O(1), but in practice this does not happen and most cases will be O(Nlogn)+O(1) and may even be O(N2)+O(1). In large volumes can go from seconds to hours.

Not to mention, you don’t run the risk of array not be classified and go wrong, as happened. And the only way to ensure in a larger code is:

  • sort every time you do binary search (very inefficient)
  • use a structure that you ensure has been sorted at first and is no longer changed
  • use a structure that automatically classifies itself every time it is changed.

It may not be what the AP wants, but it’s important for other people to know the right way to do this kind of thing and not learn wrong. Note that this is wrong even in this case proposed in the question, even if it works, unless the question is written, the performance does not matter and typing less characters matters.

Read the comments below for important extra information.

  • I did not understand exactly why the use of 'Arrays.binarySearch()' is wrong but thank you for helping me by showing an alternative way of doing.

  • 3

    Just what I said, it’s not efficient. You want to go from SP to Rio, but you don’t have a car, which is better, take a bus or buy a car just for this? Or looking the other way, which is better, walking there or manufacturing a car to go? Many should get the impression that a simple one-line method is a good thing, but what happens within it is a huge amount of processing. I wanted to do on a line just because people look more than one and think it’s worse.

  • 3

    @SDWQ12 simplifying: Arrays.binarySearch() is to be used when the vector will already be naturally ordered by your code. If it is not, it is better to use other solutions, and not binarySearch. The most obvious solution is the loop for (which is what is here in the correct answer). Perhaps language already has a linear search method, which tends to be better than binary.

  • 3

    @SDWQ12 It is important you understand the reason, to make correct decisions in the future. When you turn to a sort only to soon after do search, demonstrates ignorance of algorithms and other fundamental things, because only Sort alone consumes much more resources than one for (It will usually do more than one for internally and go through the elements more than once, as it will work on everyone and not just what you need). I recommend studying sorting algorithms, and comparing solutions.

  • 2

    @Bacco doesn’t have :D Even has that thing of Streams, but it gives even more work :D Big fault. Any language should have by default a indexOf() in (almost) all data collections.

  • 4

    @SDWQ12 "real" example. You have 600 books, mixed, and want "The Process" from Kafka. The for is you looking one by one in the sequence, and when you find it, pick it up and leave. End of story. The sort + binarySearch is you first organize ALL 600 in alphabetical order... and only after you finish ordering, start searching. Take the middle one, see if it’s what you want, if it’s not split the pile in two, look for one side, and so on, until you get to the desired one (and by ordering the book already passed several times in your hand and you did not take). Do you realize that this second alternative is not very smart?

  • 3

    What often happens is the programmer doesn’t remember that when he makes a metodoDaLinguagem() It doesn’t happen magically. It’s calling a code that does a whole series of operations. It’s a code-filled function. It simply happens that another programmer wrote the function for you and included it in the language, but it exists and the machine will have to perform all those steps (regardless of the code coming ready and you have not been presented to its source, or one that you wrote yourself).

  • I believe that we are developers and that we need to learn everything always, but the coolest of this en.stackoverflow is to know that there is another answer as the same problem cited in your answer, Because in my vision, I just wanted to expose why it didn’t work and of course I know and I wouldn’t use it to do that search. Finally, I did not see anyone go in this answer and make this fuss, because, even seems duplicate: https://answall.com/questions/12983/dificuldades-com-m%C3%A9todo-binarysearch-da-classe-arrays

  • 1

    @Virgilionovic well observed, I will complement there.

  • 1

    The only person making a fuss is you. The only person who got desperate, went out creating comments who neither crazy, editing to put information to say that your answer is wonderful, who went out looking on the site something similar is you and put in your answer as if it were a trophy, The only person who’s got a huge worry about this is you. I just gave an answer that helps people become developers and avoid the encoder syndrome that makes it work and misunderstands. I think it’s good for the community

  • 1

    You could use all this effort to find duplicates before you answer. But note that there is a difference there, several searches have been made, not just one, so it can already compensate make the classification, depends on some factors, in the case there would probably compensate.

  • @Maniero guy can say whatever you want, it doesn’t make any difference to your attitudes to me and say it as a way of being right and always right is your style. When a moderator asks to answer the question he asks only if he is sure what he will answer for me is an exclusion of people. Good thank you.

  • If it didn’t make a difference, you wouldn’t care as much as you care. Show it doesn’t make a difference by ignoring. When you decide to have all that effort you’re clearly showing that it makes a huge difference in your life.

  • I only answered you not to talk to yourself @Maniero because you’re always right.

  • 2

    @Virgilionovic I complemented, explaining the difference between a single search, and doing a Sort for several (which is the case of that one). If you have more suggestions, let me know here or there that I add if you think it is correct. Any improvement is welcome.

  • @Bacco vote as duplicate then?

  • 2

    @Virgilionovic like that is my I’m suspected to speak... It gave me the impression that has a clearer question in the sense of the problem, but as the answer is mine, I leave it to the community to decide.

  • @Bacco you saw that the array was not ordered and quoted the same thing as I did, because my concern is to answer the question in no time he said he could propose a better way to do that, so your answer is right in the same context I answered. Your answer and mine are the same and Maniero’s I see as complement not to do now I find it complicated what was done already seen that your answer is the same thing.

Show 13 more comments

4


As I reported in the commentary, binary research has the principle of ascending ordering, and its array is not so ordered from the least to the highest value. Sort with Arrays.sort that the value location is returned, example:

int vet[] = {3, 7, 6, 1, 9, 4, 5};
Arrays.sort(vet); // ordenação
int s = Arrays.binarySearch(vet, 3);
System.out.println(s);

Online Example

'Cause the weird numbers, according to Kathy Sierra’s book page 322, Successful searches return the index of the element being searched and Unsuccessful searches return an int index representing the insertion point.

I exemplified about the code of the question, we can not imagine another way if the question is described so, clear (programming is limitless) that can be done otherwise. The reasons often that led to this questioning is the explanation of the previous text, namely the lack of knowledge about what it is doing.

Remember that here on the site has an almost equal answer Difficulties with binarySearch Class Arrays method and the same solution was cited.

Of course, it could have used other forms of research, such as Linear, but, I always go by the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.