I have figured out as I am always looking to see if the value is equal to the midpoint and the value is the first value it will never be true, so how does binary search manage to find the first element in an array?
private int date_searcher(String date, ArrayList all_dates) {
found = false;
int mid_point = 0;
int first_index = 0;
int last_index = all_dates.size() - 1;
try {
find_date_parse = date_format.parse(date);
} catch (ParseException e) {
warning_disp.setText("Please input a date in the valid format");
validation = false;
}
while (first_index <= last_index & found == false & validation == true) {
mid_point = (first_index + last_index) / 2;
try { //parses the date in the mid point index
mid_point_parse = date_format.parse((String) all_dates.get(mid_point));
} catch (ParseException e) {}
if (mid_point_parse.equals(find_date_parse)) {
found = true;
} else if (mid_point_parse.after(find_date_parse)) {
last_index = mid_point + 1;
} else if (mid_point_parse.before(find_date_parse)) {
first_index = mid_point - 1;
}
}
return mid_point;
}
Your problem is with bounds when you move your indexes. Just change last instructions as followinng :
last_index = mid_point + 1; ==> last_index = mid_point - 1;
first_index = mid_point - 1; ==> first_index = mid_point + 1;