Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Rashid Mian
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rashid,

Or you can take it in this way:


So the range becomes -6 to 4
 
Nik Arora
Ranch Hand
Posts: 652
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi chandra,
Can you explain once again i didnt get?
 
Rashid Mian
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What would be the general formula, If it contains N elements.?
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic