Dewey Banks
Dewey Banks

Reputation: 323

Java: Binary Search

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;

}

}

Upvotes: 2

Views: 389

Answers (2)

Ashutosh Jha
Ashutosh Jha

Reputation: 1523

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.

Upvotes: 1

Naman
Naman

Reputation: 32046

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
}

Upvotes: 1

Related Questions