• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

range of a Arrays.binarySearch() method?

 
Tanakorn Numrubporn
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Again, This question is derive for K&B Book from Chapter7: Generics and Collections in the Self Test section:
9.Given a properly prepared String array containing five elements, which range of results could a proper invocation of Arrays.binarySearch() produce?
...
E. -5 through 4
F. -5 through 5
G. -6 through 4
...
The answer is G.
Why not answers E. Because the insertion point is -(Insertion point) -1. This string array has five elements so max index is 4 and the min insertion point should be -4 -1 = -5. I don't understand, why this array min insertion point is -6
 
Priya Viswam
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Negative value indicates unsuccessful search and [-(Insertion point) -1 ]specifies where to insert the element.

The array already contains elements in positions 0,1,2,3 and 4. So we can insert elements from 5 onwards. So the answer should be G itself since
-(-6)-1 = 5.
 
Tanakorn Numrubporn
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If the max search index is 4 that means there are 5 object in the collection.Lets name then A-E for then the insertion points will be 6(5 before each elements and 1 at the end).
search index:
[0 1 2 3 4 ]
| A | B | C | D | E
insertion points
[-1 -2 -3 -4 -5 -6(end)]
[ January 09, 2007: Message edited by: Sanjeev Kumar Singh ]
 
Tanakorn Numrubporn
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you again for knowledgh that I gain.
But which of the two above replies is correct assume about the insertion point; between the first position that we can insert in array OR the space between adjacency elements of the array.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic