如何解决二分查找找不到数组列表中的第一个值
我已经想通了,因为我一直在寻找该值是否等于中点并且该值是第一个永远不会为真的值,那么二分搜索如何设法找到数组中的第一个元素?
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;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。