programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Liutauras Vilda
• Ron McLeod
• Jeanne Boyarsky
• Paul Clapham
Sheriffs:
• Junilu Lacar
• Tim Cooke
Saloon Keepers:
• Carey Brown
• Stephan van Hulst
• Tim Holloway
• Peter Rooke
• Himai Minh
Bartenders:
• Piet Souris
• Mikalai Zaikin

# Binary Search doubt

Ranch Hand
Posts: 58
• Number of slices to send:
Optional 'thank-you' note:
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

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

Greenhorn
Posts: 28
• Number of slices to send:
Optional 'thank-you' note:
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.....

Sheriff
Posts: 11343
• Number of slices to send:
Optional 'thank-you' note:
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...

 Consider Paul's rocket mass heater.