2

Is this an ok implementation of the binary search algorithm? It works but its an implementation I came up with and differs from my instructors. Can anyone punch a hole in it for me?

package algorithm.linearsearch;

public class BinarySearch {

public static void main(String[] args) {
    System.out.println(binarySearch(
            new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 26, 109, 1001, 1100 },
            26));

}

private static int binarySearch(int[] array, int target) {
    int p = 0;
    int r = array.length - 1;
    int q;

    while (p <= r) {
        q = (p + r) / 2;
        if (array[q] == target) {
            System.out.println("value: " + array[q]);
            return q;
        }
        if (array[q] > target) {
            r = q + 1;
        } else {
            p = q - 1;
        }

    }

    return -1;

}

}

3
  • what was your instructor implementation ? Commented Aug 27, 2017 at 3:22
  • 1
    You can also give a try to binarySearch using recursive algo. Commented Aug 27, 2017 at 7:29
  • 1
    It sounds like you're asking for a code review. Commented Aug 27, 2017 at 8:52

2 Answers 2

1

Just this

if (array[q] > target) {
    r = q + 1;
} else {
    p = q - 1;
}

should be

if (array[q] > target) {
    r = q - 1; // index lower to current pivot
} else {
    p = q + 1; // index upper to current pivot
}
Sign up to request clarification or add additional context in comments.

1 Comment

@nullpointer you missed chance of null pointer. Of all people you should not miss it as its your username :D
1

One thing i can say. Your program is expected to return index if found or return -1 if not found. So you don't need to print value as its input taken from user regarding which element to find.

You need a check initially if your array is null return -1 to avoid null pointer exception which will happen when you calculate length of array.

Comments

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.