Results 1 to 2 of 2
  1. #1
    adurga is offline Member
    Join Date
    Nov 2012
    Posts
    5
    Rep Power
    0

    Default 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

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default 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.

    ** This space for rent **

Similar Threads

  1. Having problem with Arrays.binarySearch()
    By xEnOn in forum New To Java
    Replies: 13
    Last Post: 05-10-2011, 06:04 PM
  2. Method Arrays's: Returning multiple values
    By noobForever in forum New To Java
    Replies: 6
    Last Post: 11-02-2010, 01:07 PM
  3. SortedSet and Collections.binarySearch
    By ninoid in forum New To Java
    Replies: 4
    Last Post: 03-22-2010, 04:28 PM
  4. Replies: 4
    Last Post: 02-13-2009, 08:42 AM
  5. returning arrays
    By cjohnson412 in forum New To Java
    Replies: 4
    Last Post: 11-25-2008, 02:30 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •