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
• Liutauras Vilda
• Tim Cooke
• Jeanne Boyarsky
• Paul Clapham
Sheriffs:
• Devaka Cooray
• Ron McLeod
• paul wheaton
Saloon Keepers:
• Tim Moores
• Piet Souris
• Tim Holloway
• Stephan van Hulst
• Carey Brown
Bartenders:
• Al Hobbs
• Frits Walraven
• Scott Selikoff

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

Ranch Hand
Posts: 31
• Number of slices to send:
Optional 'thank-you' note:
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?

Ranch Hand
Posts: 2412
• Number of slices to send:
Optional 'thank-you' note:
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.

Ranch Hand
Posts: 1710
• Number of slices to send:
Optional 'thank-you' note:
Hi Rashid,

Or you can take it in this way:

So the range becomes -6 to 4

Ranch Hand
Posts: 652
• Number of slices to send:
Optional 'thank-you' note:
Hi chandra,
Can you explain once again i didnt get?

Rashid Mian
Ranch Hand
Posts: 31
• Number of slices to send:
Optional 'thank-you' note:
What would be the general formula, If it contains N elements.?

Chandra Bhatt
Ranch Hand
Posts: 1710
• Number of slices to send:
Optional 'thank-you' note:

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.

 It wasn't my idea to go to some crazy nightclub in the middle of nowhere. I just wanted to stay home and cuddle with this tiny ad: the value of filler advertising in 2021 https://coderanch.com/t/730886/filler-advertising