二进制搜索找不到数组列表中的第一个值
Binary Search cannot find the first value in the array list
我已经弄清楚了,因为我一直在寻找该值是否等于中点并且该值是第一个值,它永远不会为真,那么二进制搜索如何设法找到第一个元素数组?
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;
}
改变最后的指令如下last_index = mid_point + 1; ==> last_index = mid_point - 1; first_index = mid_point - 1; ==> first_index = mid_point + 1;
已解决问题,谢谢 g.momo
我没有检查,但我认为你应该改变这个:
last_index = mid_point - 1;
first_index = mid_point + 1;
您的问题出在移动索引时的范围上。
只需更改最后的说明如下:
last_index = mid_point + 1; ==> last_index = mid_point - 1;
first_index = mid_point - 1; ==> first_index = mid_point + 1;
我已经弄清楚了,因为我一直在寻找该值是否等于中点并且该值是第一个值,它永远不会为真,那么二进制搜索如何设法找到第一个元素数组?
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;
}
改变最后的指令如下last_index = mid_point + 1; ==> last_index = mid_point - 1; first_index = mid_point - 1; ==> first_index = mid_point + 1;
已解决问题,谢谢 g.momo
我没有检查,但我认为你应该改变这个:
last_index = mid_point - 1;
first_index = mid_point + 1;
您的问题出在移动索引时的范围上。 只需更改最后的说明如下:
last_index = mid_point + 1; ==> last_index = mid_point - 1;
first_index = mid_point - 1; ==> first_index = mid_point + 1;