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);
}
