binary search


See On Github

Data

Source Code

import java.util.Arrays;

public class BinarySearch {
    public static int search(int[] values, int target) {
        if (values.length < 1) {
            return -1;
        }

        int mid = values.length / 2;
        int midValue = values[mid];

        if (midValue > target) {
            return search(Arrays.copyOfRange(values, 0, mid), target);
        } else if (midValue < target) {
            int p = search(Arrays.copyOfRange(values, mid + 1, values.length), target);
            return (p < 0) ? -1 : mid + 1 + p;
        }
        return mid;
    }
}
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;


@RunWith(JUnit4.class)
public class BinarySearchTest {
    int[] values = {1, 3, 5, 9, 17};
    int expectedPosition = 3;
    int target = 9;

    @Test
    public void shouldFindANumber() {
        int result = BinarySearch.search(values, target);
        Assert.assertEquals(expectedPosition, result);
    }

    @Test
    public void shouldFindNothing() {
        int result = BinarySearch.search(values, 19);
        Assert.assertEquals(-1, result);
    }

}