Negative return of Array.BinarySearch ()

2

I needed to make a comparison of the genre of methods normally created as inList or something of the sort. Searching the Microsoft documentation, I found Array.BinarySearch(T[], T) . I made 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

    
asked by anonymous 01.02.2016 / 18:44

1 answer

4

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

  

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 bitwise complementary 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 .

If you make up the ranking before doing the search it will depend on a number of factors, such as how many times you need to search, the size of the array , available resources, etc. < p>

I hope you're using the generic version of the method .

Moral of the story: Before using anything, read the documentation.

    
01.02.2016 / 18:52