我正在开发一个项目,在该项目中,它从.txt文件中读取书名并将它们放入arraylist,然后将arraylist转换为数组,用户输入一个数字作为书籍参考编号,然后它进行线性搜索和二进制搜索以查找该书。我只是遇到了二进制搜索的代码问题,就我的二进制搜索知识而言,这就是我所放在一起的,所以我的二进制搜索代码有什么问题?
int left = 0,right = bookList.length;
int int1;
int1 = Integer.parseInt(input);
while(left <= right){
int middle = (right + left)/2;
int compare = input.compareTo(bookList[middle].referenceNumber);
if(compare == 0){
Output2.setText("The book is " + bookList[middle].title);
} else if(compare < int1){
right = middle - 1;
left = 0;
if(compare == 0){
Output2.setText("The book is " + bookList[middle].title);
}
} else if(compare > int1){
right = bookList.length;
left = middle + 1;
if(compare == 0){
Output2.setText("The book is " + bookList[middle].title);
}
}
}
以下是我的书类和书单数组
public class Book{
String referenceNumber, title;
public Book(String _referenceNumber, String _title){
referenceNumber = _referenceNumber;
title = _title;
}
}
ArrayList <Book> Books = new ArrayList <Book> ();
Book [] bookList;
感谢您提供的任何帮助
答案 0 :(得分:0)
缩小范围时,请勿将左侧设置为零或右侧设置为.length。你必须保留旧的值。
int left = 0,right = bookList.length;
int int1;
int1 = Integer.parseInt(input);
while(left <= right){
int middle = (right + left)/2;
int compare = input.compareTo(bookList[middle].referenceNumber);
if(compare == 0){
Output2.setText("The book is " + bookList[middle].title);
} else if(compare < int1){
right = middle - 1;
if(compare == 0){
Output2.setText("The book is " + bookList[middle].title);
}
} else if(compare > int1){
left = middle + 1;
if(compare == 0){
Output2.setText("The book is " + bookList[middle].title);
}
}
}