Results 1 to 2 of 2
- 12-07-2012, 01:13 PM #1
Member
- Join Date
- Nov 2012
- Posts
- 5
- Rep Power
- 0
binarysearch in Arrays returning -ve value for an existing key
Hi,
For the below code, the key "why" does not exist hence -1 justified but for the key "java" why -3 is being given as the output?
Java Code:import java.util.Arrays; public class Test3 { public static void main(String[] args) { String[] arr1 = { "java", "champ", "you" }; System.out.println(Arrays.binarySearch(arr1, "java")); System.out.println(Arrays.binarySearch(arr1, "you")); System.out.println(Arrays.binarySearch(arr1, "Why")); } } Output is -3 2 -1
- 12-07-2012, 01:57 PM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,467
- Rep Power
- 16
Re: binarysearch in Arrays returning -ve value for an existing key
From the API:
"The array must be sorted into ascending order according to the natural ordering of its elements (as by the sort(Object[]) method) prior to making this call. If it is not sorted, the results are undefined."
Your array is not sorted.Please do not ask for code as refusal often offends.
Similar Threads
-
Having problem with Arrays.binarySearch()
By xEnOn in forum New To JavaReplies: 13Last Post: 05-10-2011, 05:04 PM -
Method Arrays's: Returning multiple values
By noobForever in forum New To JavaReplies: 6Last Post: 11-02-2010, 12:07 PM -
SortedSet and Collections.binarySearch
By ninoid in forum New To JavaReplies: 4Last Post: 03-22-2010, 03:28 PM -
how does public static <AnyType extends Comparable<? super AnyType>> int binarySearch
By JordashTalon in forum New To JavaReplies: 4Last Post: 02-13-2009, 07:42 AM -
returning arrays
By cjohnson412 in forum New To JavaReplies: 4Last Post: 11-25-2008, 01:30 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks