This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
from the K&B Master Exam there is a question along the lines of:
'If you have a properly prepared list of five elements,what range of results could the binarySearch() method return?'
The answer:-6 to 4(I think)
Now I know that binarySearch,if the item is not found will return the appropriate index to maintain the sort order by inverting and decr4ementing the appropriate index.
So.. a list of 5 elements:
list =>returns -1 if the item is not found and should be placed here
list=>returns -2 if the item is not found and should be placed here
list=>returns -3 if the item is not found and should be placed here
list=>returns -4 if the item is not found and should be placed here
list =>returns -5 if the item is not found and should be placed here
The results would return -5 to 4...
What am I missing here?
You are forgetting the case where you are looking for an element which is above the last one. For example, when you look for 6 in an array containing five elements (1,2,3,4,5), the index where 6 should be inserted is 5 : -5 - 1 = -6.
Then should return -1.
Because "Ant" would precede any of the items in the list according to Sring's natural order and therefore be appropriate at index...inverted and decremented:
Can't invert 0 but decrementing results in the index of [-1].
Likewise, should return [-3] to fit in between Dog and Mouse.