• Post Reply Bookmark Topic Watch Topic
  • New Topic
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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

K&B page 628 question 9

 
Ranch Hand
Posts: 189
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Given a properly prepared String array containing 5 elements, which range of results could be 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


I responded E (-5 through 4), but in the book the correct response is G(-6 through 4). Could someone explain me why G and not E ?

Regards
 
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I guess you are clear with the most positive value that will be returned after a successful search i.e. 4 because there are only 5 elements present.

Now if we consider the results for negative values i.e. for the insertion of elements to maintain the sort order then there are three cases which we can have:

1. Insertion at the start of the Array i.e. at index 0 : In this case the binarySearch will return [-(insertion point)-1] i.e. [-(0)-1]=-1

2. Insertion at the end of the Array i.e. at index 5(Not 4 because a new element needs to be added) : For this the result will be [-(5)-1]=-6

3. Insertion at any place other than the above two: In that case the result will be between -2 and -5 both inclusive.

I hope you this should help you!!!

Thanks
Hemnath
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic