• 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:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

binarySearch(). (Objective 6.5)

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In connection to self test question no. 9 at the end of chapter 7 in the SCJP 1.5 book by K&B.

Please Elucidate the following answer:-

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:
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.
 
Ranch Hand
Posts: 652
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Divya,
Look at the below formula. Where "N" stands for number of elements and since there 5 elements it will be

-(N+1) to (N-1)

-(5+1) to (5-1)

-6 to 4

regards
 
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

Divya

Welcome to JavaRanch


If we are having 5 elements in the list means
the index starts from 0 and ends with 4
ok
And these are strings means they are sorted properly
ok
now you are searching an element,and that element was not there.
then what you will get an insertinon as -6,invert and then decremented -1 that gives us index,where that element would be there.

And check the answers .

I think you have understood.


Thanks
Anil Kumar
 
Divya Tiwari
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot. That helped.
 
You can't expect to wield supreme executive power just because
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic