• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why does Arrays.binarySearch returning that value?

 
Rancher
Posts: 163
5
Eclipse IDE Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello!



Why does returned value equals -4 ?
If I add 0 at the end of the array,  it will be -5, but if I add a 3 instead of 0, it will be 3. Then I add 3 and 45 ( {3,2,1,0,3,45} ) and it will 4...

I know, the returned value is not defined for not sorted array, but I think it is important to understand why this values and not other.

P.S. Explanation in the book OCAJ SE8 from Selikoff&Boyarsky on page 126 is not enough.

Best regards
Mike Savvy
 
Saloon Keeper
Posts: 15524
364
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mike Savvy wrote:I know, the returned value is not defined for not sorted array, but I think it is important to understand why this values and not other.


It's not important. Undefined means undefined.

While it's not important, it might be interesting.

The reason is that it first compares 3 to the value at the middle of the array, which is 2. It sees that 3 is greater, so it then continues to the right half of the array. It sees that 3 is greater than 1, so it continues to the right of 1. There are no more elements there, and it hasn't found the value 3, so instead of returning the index of the found element, it returns (-(insertion point) - 1).

For an insertion point of 3 (the index to the right of value 1), the return value is (-(3) - 1) = -4.
 
Mike Savvy
Rancher
Posts: 163
5
Eclipse IDE Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I see, thank you Stephan van Hulst!
 
reply
    Bookmark Topic Watch Topic
  • New Topic