[英]Using a Bubble Sort Algorithm, Sort an arrayList of objects alphabetically
基本上,我有一個學生班,它閱讀包含姓名、年齡和學號的紡織品。 我將所有這些都存儲在類的數組列表中。
//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
獲取名稱()。 方法獲取學生的姓氏。 我不確定如何排序。 使用 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());
}
}
}
您可以在此處驗證結果:在線排序工具
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.