Java binary search implementation.

public class App {

    public static void main(String[] args) {
        int[] nums = {-3, 0, 1, 2, 3, 4, 6, 7};
        System.out.println(Arrays.binarySearch(nums, 6));
        System.out.println(binarySearch(nums, 6));
    }

    public static int binarySearch(int[] nums, int num) {
        int low = 0;
        int high = nums.length - 1;
        int index = -1;
        while (low <= high) {
            int mid = (high - low) / 2 + low;
            int midNum = nums[mid];
            if (num == midNum) {
                index = mid;
                break;
            } else if (num > midNum) {
                low = mid;
            } else {
                high = mid;
            }
        }
        return index;
    }
}
Post tagged with: java, algorithm