Binary search in unsorted array

adamson :

I came across this problem: Given unsorted array, find how many elements can be found using binary search - ex : [5,4,6,2,8] -> Ans : 3 -> '6' and '8' and '5' can be found using binary search

I can't even understand what it means to do a binary search on unsorted array. Can someone please explain the problem?

There's also a code that solves this problem:

private static int countPossibleMatches(int[] array, int left, int right, int min, int max) {
        if (right < left) {
            return 0;
        } else if (right == left) {
            return (array[left] >= min && array[left] <= max? 1 : 0);
        } else {
            int middle = (left + right) / 2;
            int count = (array[middle] >= min && array[middle] <= max ? 1 : 0);
            count += countPossibleMatches(array, left, middle - 1, min, Math.min(array[middle], max));
            count += countPossibleMatches(array, middle + 1, right, Math.max(array[middle], min), max);
            return count;
        }
    }

    static int countPossibleMatches(int[] array) {
        return countPossibleMatches(array, 0, array.length - 1, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }
Eran :

Binary search doesn't work for unsorted arrays. That said, if you ignore the fact that the array is unsorted and you run binary search algorithm on it, for some inputs it might succeed in finding the index of the element you are looking for.

For example, the first step of the binary search algorithm requires you to check the element are the middle index of the array. Therefore, if you are searching for the element that happens to be in that position, your binary search will find it, regardless of whether or not the array is sorted.

Therefore

find how many elements can be found using binary search

asks you to answer for a given array, how many of its elements can be found via binary search algorithm.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=155837&siteId=1