Negative return from Array.Binarysearch()

Asked

Viewed 88 times

3

I needed to make a comparison of the kind of methods normally created as inList or something like that. When searching the Microsoft documentation, I found the Array.BinarySearch(T[], T). I performed this operation in my code and I was in doubt with the return that was -36.

Array.BinarySearch(new Int32[] { 1, 2, 3, 20, 25, 30, 31, 34, 36, 37, 39, 40, 41, 42, 43, 44, 45, 6, 12, 14, 17, 18, 27, 48, 4, 10, 11, 19, 21, 22, 23, 24, 26, 28, 29, 32, 33, 35, 38, 46, 13, 5, 15, 16, 47, 49, 7, 8, 9 }, clalav_lav)
//O valor da variável clalav_lav é 30 no momento

Why did he return -36, if the value exists in the array?

1 answer

5


The reason is simple, a binary search, as the documentation says, can only be performed in a sequence of previously classified data. Without this condition being met the result is determined as negative, again according to the documentation. In the clearly presented case a classification is missing.

Searches an entire one-dimensional Sorted array for a specific element, using the Icomparable Generic interface implemented by each element of the Array and by the specified Object.

Return:

The index of the specified value in the specified array, if value is found; otherwise, a Negative number. If value is not found andvalue is Less than one or more Elements in array, the Negative number returned is the bitwise Complement of the index of the first element that is Larger than value. If value is not found and value is Greater than all Elements in array, the Negative number returned is the bitwise Complement of (the index of the last element plus 1). If this method is called with a non-sorted array, the Return value can be incorrect and a Negative number could be returned, Even if valueis present in array.

Whether it pays to rank before doing the search will depend on a number of factors, among them, how many times you will need to do the search, the size of the array, available resources, etc.

I hope you’re wearing the generic version of the method.

Moral of the story: before using anything read the documentation.

  • Gee, in the middle of the rush, I didn’t notice the OBVIOUS! Thank you very much.

Browser other questions tagged

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