GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Binary Search doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Binary Search doubt" Watch "Binary Search doubt" New topic
Author

Binary Search doubt

mukki pandey
Ranch Hand

Joined: Sep 22, 2008
Posts: 58
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

Answer:
3 G is correct. 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.
A, B, C, D, E, F, and H are incorrect based on the above. (Objective
6.5)

Can any one please expalin me why only G

Source KB Book
Jeevitesh Singh
Greenhorn

Joined: Jun 19, 2008
Posts: 28
hi friend.....
you must be knowing if it gets a match it returns the index......
therefore you must be understanding 0 to 4.......
for the ans of -6 to -1 is
that index returned for no match is
as (-(insertion point)-1)....we have insertion points as .....
0,1,2,3,4,5......
5 because we can insert it after the last element......
putting these in the formula you will have -1 to -6.....
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

The API says a binary search returns the...
...index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key.

So for a sorted array containing 5 elements...


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Binary Search doubt