Results 1 to 5 of 5

Thread: Need help

  1. #1
    radhi16 is offline Member
    Join Date
    Jan 2011
    Posts
    30
    Rep Power
    0

    Default Need help

    I have written a code to sort an array :
    Java Code:
    int arr[] = {95, 20, 34, 1, 9, 78, 3};
            int index = 0;
            Arrays.sort(arr, 0, arr.length);
            System.out.println(Arrays.toString(arr));
            index = Arrays.binarySearch(arr, 9);
            System.out.println("The index of 9 is:" + index);
    I can use Arrays.binarySearch(arr, 9) only when my array is ascending order.Is there any api in java which allows me to use without sorting the array in ascending order.

  2. #2
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    I cant see anyway binary search can work on a non sorted array, if you jump to halfway through an array how do you know whether you should go left or right if both sides can have numbers greater than and less than the middle element.

  3. #3
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,755
    Rep Power
    7

    Default

    The only way to search an unordered list is a linear search. Just think about a phone book. How would you find someone's name if it was not sorted alphabetically?

  4. #4
    falkon114 is offline Member
    Join Date
    Dec 2010
    Posts
    18
    Rep Power
    0

    Default

    Quote Originally Posted by Junky View Post
    The only way to search an unordered list is a linear search. Just think about a phone book. How would you find someone's name if it was not sorted alphabetically?
    Start at the beginning and go forward ;)
    OP: binary only works for sorted, as has been pointed out. try the code linearSearch() instead

  5. #5
    radhi16 is offline Member
    Join Date
    Jan 2011
    Posts
    30
    Rep Power
    0

Posting Permissions

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