This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Given a properly prepared String array containing five elements, which range of results could a proper invocation of Arrays.binarySearch() produce? A. 0 through 4 B. 0 through 5 C. -1 through 4 D. -1 through 5 E. -5 through 4 F. -5 through 5 G. -6 through 4 H. -6 through 5
The Answer is: G
Explanation given in the book is:
If a match is found, binarySearch()will return the index of the element that was matched. If no match is found, binarySearch() will return a negative number that, if inverted and then decremented, gives you the insertion point (array index) at which the value searched on should be inserted into the array to maintain a proper sort.
I have some problem in understanding this answer. The problem I have marked in bold.
now as you can see that 15 is not in the list. But if you want to keep your array sorted, then you must insert 15 at index 1 i.e. between 10 and 20. So the returned value will be -2. If you invert the value of -2 (by doing 1's complement as ~(-2)), you will get 1. Similarly if you search for 45, you will get -6 as inverting -6 will result in 5 which is the correct position for 45.