I have an array with boolean values. But sequence of elements like these:
first go true values, and then false values.
For example,
boolean[] booleans = {true, true, true, true, true,
false, false, false, false, false, false};
So now we have a sorted array with boolean values, starting with true values if true value exists.
The task is to find first false element.
I created a class with search method using binary search algorithm.
public class BinarySearch {
public static int search(boolean[] array) {
int low = 0, mid = 0;
int high = array.length - 1;
boolean booleanValue;
while (low <= high) {
mid = (low + high) >>> 1;
booleanValue = array[mid];
if (booleanValue) low = mid + 1;
else high = mid - 1;
}
return mid == array.length - 1 ? -(low + 1) : mid;
}
public static void main(String[] args) {
boolean[] booleans = {true, true, true, true, true,
false, false, false, false, false, false};
int search = search(booleans);
System.out.println("search = " + search);
}
}
It is not working correct, i.e. sometimes it is returning previous element of searched one.
Finding element by searching iteratively is also not good idea, because array's size could be really big, and it will take much time.
Edit: Actually I need to search in MySQL database table. But table size is too big, and finding required row takes to much time, I want to use binary search algorithm for fastening.
Edit: MySQL table size more than 45 million rows. It takes about 30 seconds when searching required row by SQL query, no matter I added index to the column or not. Furthermore adding index in boolean doesn't give any effect.
When I use binary search it takes about 10 milliseconds. So I want the above method to be corrected.
Edit: For instance, I have DB table called "INFORMATION". And it has two columns "INFO" (TEXT) and "CHECKED" (BOOLEAN). Initial values of "INFO"s are false. And I will get first unchecked info, and get N rows starting from unchecked, then I will check them and mark them true. Process will be repeated until there is no unchecked infos.