Reputation: 49
Trying to figure this out
Declared an Array int[] iArray = {6, 12, 3, 9}
Ran Binary search for the number 9
return value is -2
Can someone explain to me why?
Do I have to Sort the array before I run the Binary Search in order to get the desired result? I am confused lol
Upvotes: 0
Views: 55
Reputation: 850
you get a -2 because the 9 you are looking for would go between the first and second index of the list. That is where it would have been inserted (between 6 and 9if it was sorted).
{http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch%28int[],%20int%29}
Upvotes: 2
Reputation: 625
Yes, binary search only works on sorted data. Can't explain why the -2 tho.
Upvotes: 0