【发布时间】:2021-03-15 18:13:23
【问题描述】:
我现在有一个问题,我有一个大学作业,我们需要列出一个包含书籍的文件,并且应该从 A 到 Z 排序,
我的排序算法是冒泡排序,目前没有按字母顺序排序,但没有给出错误,我看不出我应该改变哪里才能让它工作,因为编码对我来说似乎是正确的。
我们不允许使用集合,所以这就是我不使用 sort() 的原因。
package Book;
public class AlphabeticalOrderTitle{
//Global variables
public static String input;
public static int bookId;
public static String bookTitle;
public static String authorName;
public static boolean isAvailable;
public static void main(String[] args)
{
ArrayList<Book> books = BubbleSort();
System.out.println(linearSearch(books));
}
public static ArrayList<Book> loadData() {
//Creating an array list;
ArrayList<Book> books = new ArrayList<>();
try {
//Here we start reading our file
BufferedReader br = new BufferedReader(new FileReader("Book.txt"));
//This header string will allow to skip the header so does not mismatch with getter and setters.
String header = br.readLine();
//This string will read the lines.
String contentLine = br.readLine();
//Giving our array name data;
String [] data;
//Here we loop to continue the reading of data for each array box.
while (contentLine != null) {
data = contentLine.split(",");
bookId = Integer.parseInt(data[0]);
bookTitle = data[1];
authorName = data[2];
isAvailable = Boolean.parseBoolean(data[3]);
books.add(new Book(bookId, bookTitle, authorName, isAvailable));
contentLine = br.readLine();
}
}catch (IOException ex) {
Logger.getLogger(SearchBookAuthor.class.getName()).log(Level.SEVERE, null,ex);
}
return books;
}
public static int linearSearch(ArrayList<Book> array){
//Variables for holding values
int n;
String temp;
// Going one by one the elements in the array
for(int g = 0; g < array.size(); g++){
//Getting the array size from the file and giving the array name a size
n = array.size();
String names[] = new String[n];
//Load all the names
for(int i = 0; i < n; i++) {
names[i] = array.get(g).getBookTitle();
}
//Bubble sort starts
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if (names[i].compareTo(names[j]) > 0)
{
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
//Print sorted
System.out.println(names[n-1]);
}
return -1;
}
}
输出:
Captains
Romeo
Don
-1
而我的目标是船长、唐、罗密欧。
我的 book.txt 包含是这样的: book
有什么建议可以解决吗?非常感谢。
【问题讨论】:
-
@OHGODSPIDERS 它确实发生在
linearSearch方法中 -
提示:正确的冒泡排序不需要 三层 层循环嵌套,只需 两层。
标签: java algorithm sorting arraylist bubble-sort