*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Help need: Book K&S Chapter 7, Exercise Q=9 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 "Help need: Book K&S Chapter 7, Exercise Q=9" Watch "Help need: Book K&S Chapter 7, Exercise Q=9" New topic
Author

Help need: Book K&S Chapter 7, Exercise Q=9

Rashid Mian
Ranch Hand

Joined: Feb 14, 2007
Posts: 31
9.
Given a properly prepared String array containing five elements, which range of results could a proper invocation of Arrays.binarysearch() produce?

0 through 4

0 through 5

- 1 through 4

-1 through 5

- 5 through 4

-5 through 5

-6 through 4

- 6 through 5

My answer is it should be - 5 through 4?
Can any one help?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Remember the way the binary search works.

If it doesn't find the number you're looking for, the method returns -(insertion point) - 1 where insertion point is the place in the array the element would go.

Consider this example.

Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi Rashid,

Or you can take it in this way:


So the range becomes -6 to 4


cmbhatt
Nik Arora
Ranch Hand

Joined: Apr 26, 2007
Posts: 652
Hi chandra,
Can you explain once again i didnt get?
Rashid Mian
Ranch Hand

Joined: Feb 14, 2007
Posts: 31
What would be the general formula, If it contains N elements.?
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Originally posted by Rashid Mian:
What would be the general formula, If it contains N elements.?



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

eg. For five elements
-(5+1) to (5-1)
=-6 to 4



Hi chandra,
Can you explain once again i didnt get?


What didn't you understand exactly? Do some practice with binarySearch(...)
you will get exact idea.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Help need: Book K&S Chapter 7, Exercise Q=9