使用冒泡排序算法,按字母顺序对对象的 arrayList 进行排序

Using a Bubble Sort Algorithm, Sort an arrayList of objects alphabetically

基本上我有一个学生 class 阅读一个包含姓名、年龄和学号的纺织品。我将所有这些存储在带有 class.

的数组列表中
  //method for ordering student accounts by last name (bubble sort) alphabetically
 public static void alphabetOrder(ArrayList<Student> users)throws IOException{
  
    int k = 0;
    boolean exchangeMade = true;
    while ((k < users.size() - 1) && exchangeMade) {
        exchangeMade = false; // no exchange has been made yet
        k++; // increment the index
        for (int j = 0; j < users.size() - k; j++) {
            if(users.get(j).getName().compareTo(users.get(j+1).getName()){
                swap(users, j, j+1);
                exchangeMade = true;
            }
        } 
    }


  public static void swap(ArrayList<Student> users, int x, int y) {
    Student temp = users.get(x); // set temp value to element at index x
    users.set(x, users.get(y)); // set value at index x to the value at index y
    users.set(y, temp); // set value at index y to the temp value 
    
} // end of swap method
 

getName()。方法获取学生的姓氏。我不确定如何对此进行排序。使用 name.charAt(i) 然后通过它进行一些排序会更好吗?

请试试这个:

import java.util.ArrayList;
import java.util.List;

public class BubbleSortAlph {

    public static void alphabetOrder(List<Student> users) {

        int k = 0;
        boolean exchangeMade = true;
        while ((k < users.size() - 1) && exchangeMade) {
            exchangeMade = false; // no exchange has been made yet
            k++; // increment the index
            for (int j = 0; j < users.size() - k; j++) {
                if (users.get(j).getName().compareTo(users.get(j + 1).getName()) > 0) {
                    swap(users, j, j + 1);
                    exchangeMade = true;
                }
            }
        }
    }


    public static void swap(List<Student> users, int x, int y) {
        Student temp = users.get(x); // set temp value to element at index x
        users.set(x, users.get(y)); // set value at index x to the value at index y
        users.set(y, temp); // set value at index y to the temp value

    } // end of swap method

    public static void main(String[] args) {
        List<Student> users = new ArrayList<>();

        Student student1 = new Student("1234");
        Student student2 = new Student("234");
        Student student3 = new Student("_1234");
        Student student4 = new Student("a");
        Student student5 = new Student("b");
        Student student6 = new Student("ab");

        users.add(student5);
        users.add(student1);
        users.add(student3);
        users.add(student4);
        users.add(student6);
        users.add(student2);

        alphabetOrder(users);

        for (Student student : users) {
            System.out.println(student.getName());
        }
    }
}

您可以在这里验证结果:online sort tool