1

Recently I study algorithms,but I find a terrible problem that I cannot find the number by BinarySearch Algorithm in the link: http://algs4.cs.princeton.edu/11model/BinarySearch.java.html

public class BinaryFind {

    public static int indexOf(int[] a, int key) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            // Key is in a[lo..hi] or not present.
            int mid = lo + (hi - lo) / 2;
            if (key < a[mid]) hi = mid - 1;
            else if (key > a[mid]) lo = mid + 1;
            else return mid;
        }
        return -1;
    }


    public static void main(String[] args) {
        int[] a = {1, 4, 56, 4, 3, 7, 8, 2, 66, 45};
        System.out.print(indexOf(a, 7));

    }
}

Why I cannot find the number 7?

The result:
enter image description here

2
  • 3
    The basic principle behind a binary search is that the input array has to be sorted. You missed that part. Commented Mar 15, 2016 at 3:38
  • Sure,you are right Commented Mar 15, 2016 at 3:59

2 Answers 2

1

Add this line to the top of the indexOf(..) method.

Arrays.sort(a);

This will sort your input array and then you can go on with finding the index.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I know,the BinarySearch Algorithm should in a sorted array! I am a newbie in algorithm, thank you very much!@Debosmit Ray
@Pisces Sure thing. It would be nice, if you could accept an answer if your issue is resolved. From here, "Accepting an answer is important as it both rewards posters for solving your problem and informs others that your issue is resolved."
1

The array to be searched from have to be sorted to use binary search.

Try this:

public static void main(String[] args) {
    int[] a = {1, 4, 56, 4, 3, 7, 8, 2, 66, 45};

    // sort the array
    for (int i = a.length - 1; i > 0; i--) {
        for (int j = 0; j < i; j++) {
            if (a[j] > a[j + 1]) {
                int t = a[j];
                a[j] = a[j + 1];
                a[j + 1] = t;
            }
        }
    }

    System.out.print(indexOf(a, 7));

}

1 Comment

You're right. But the example code the OP has linked to also uses Arrays.sort(whitelist);. So, it seems permissible to use the built-in method for this ...homework(?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.