Skip to content
Advertisement

Getting unexpected position value from binarySearch method in java

Currently working with java basics.While learning I’ve written the following code.

JavaScript

My expected output:

Element 1 at 3

Element 2 at 5

Element 3 at 6

Element 1 at 3

Element 5 at 4

Element 2 at 5

Element 3 at 6

My actual output:

Element 1 at 3

Element 2 at 5

Element 3 at 6

Element 1 at 3

Element 5 at -8

Element 2 at 5

Element 3 at 6

In my actual output at element 5 why I’m getting -8 from Arrays.binarySeach(out,each) function?

Explain me this please.

Advertisement

Answer

Always remember for binary search to work you must sort the array. Use can use Arrays.sort() for sorting

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement