public static int binarySearch(ArrayList<Integer> a, int x) {
        int low = 0;
        int high = a.size() - 1;
        int mid=0;

        while (low <= high) {
            mid = (low + high) / 2;

            if (a.get(mid) < x) {
                low = mid + 1;
            } else if (a.get(mid) > x) {
                high = mid - 1;
            } else {
                return mid;
            }
        }
        return ~mid;
    }