This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes binary search 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" Watch "binary search" New topic

binary search

hari harann
Ranch Hand

Joined: Aug 07, 2008
Posts: 54
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.
but i feel option G is incorrect, the answer is option E. am i right??
Pranav Bhatt
Ranch Hand

Joined: Mar 20, 2006
Posts: 284
Hi Hari,
The range will be from -6 through 4 As the array is of 5 elements so if you insert any element that comes at last like ZZZ. This will give you -6 as it will come after the last 5th element. If you happen to insert the fifth element to get the highest range value you will end up with 4 as elements are from 0->4(5 elements). Check the below prog-:
hari harann
Ranch Hand

Joined: Aug 07, 2008
Posts: 54
Thanks pranav
Ankit Garg

Joined: Aug 03, 2008
Posts: 9400

Hey Pravan I modified your code. I think this will make it more understandable.

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Pranav Bhatt
Ranch Hand

Joined: Mar 20, 2006
Posts: 284
Hey Ankit, Its Pranav . Thanks for the modification, am bit lazy here
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link:
subject: binary search
It's not a secret anymore!