Java - 使用冒泡排序对数组列表进行排序时出现问题

Java - Problem at sorting array list using bubblesort

我现在有一个问题,我有一个大学作业,我们需要列出一个包含书籍的文件,应该按 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

有什么修复建议吗?非常感谢。

Bubble Sort Example

我链接了一个冒泡排序示例。您可以点击 Java 查看 Java 中的版本。你可以看到你和他们之间存在差异,即使它们非常相似。

我会做的是手动完成。也就是说,拿一些纸,写下你的阵列是什么样子,然后假装你是计算机,看看你最终得到了什么。这对你来说是一个很好的练习,你可能会弄清楚自己做错了什么。

首先,BubbleSort() 不是此方法的合适名称,因为它所做的只是读取文件并将内容存储在列表中。

如果本课程不是高级算法 class,您可能可以使用 java 库来对列表进行排序。

像这样的东西应该可以工作并产生所需的结果:
Collections.sort(书籍);

此外,我通常只执行以下操作: List books = new ArrayList<>();

如果您必须实施冒泡排序,请使用以下 link,其中显示了如何使用冒泡排序对字符串数组进行排序:https://www.geeksforgeeks.org/sorting-strings-using-bubble-sort-2/

对于数组A的'n'个元素A[n],那么冒泡排序的第一个循环总是以n-1结束。 冒泡排序的思想是比较相邻的元素,如果顺序不对则交换(根据用例增加/减少)。

因此,当 i=n-1 时,正如您在第一个 for 循环中提到的那样=>j=n-1。我们基本上是在比较 A[i=n-1] 和 A[j=n-1].

//Bubble sort starts
                  for (int i = 0; i < n-1; 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;
                          }
                      }
                  }

你可以尝试快速干燥-运行每当你遇到这样的问题时,用小数字代替并将循环内容写在纸上。对学习和建立逻辑有很大帮助。 :)

经过几天的努力,我得到了一个可行的解决方案,感谢大家。

public class Alphabetical_Order {

//Global variables
public static String input;
public static int bookId;
public static String bookTitle;
public static String authorName;
public static boolean isAvailable;

//Creating an array list;
public static ArrayList<Book> books = new ArrayList<>();

public static void main(String[] args) 
{
    loadData();
    int n = 0;
    String temp;
  //Scanner s = new Scanner(System.in);
    System.out.print("Enter number of names you want to enter:");
    
    //get size of arraylist
    for (int g = 0; g < books.size(); g ++) {
           n = books.size();

    }
    
 
    String names[] = new String[n];
    
    //Names to be get from user
    Scanner s1 = new Scanner(System.in);
    System.out.println("Enter all the names:");
    for(int i = 0; i < n; i++)
    {
        names[i] = books.get(i).getAuthorName();
    }
    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;
            }
        }
    }
    System.out.print("Names in Sorted Order:");
    for (int i = 0; i < n - 1; i++) 
    {
        System.out.print(names[i] + ",");
    }
    System.out.print(names[n - 1]);
}

public static void loadData() { 
    
    try {
        //Here we start reading our file
        BufferedReader br = new BufferedReader(new FileReader("Book.csv"));
        
        //This header string will allow to store the header so does not mistach 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);
    } 

    
}}