gpt4 book ai didi

java - 排序数组: Bubble sort

转载 作者:行者123 更新时间:2023-12-01 21:58:37 25 4
gpt4 key购买 nike

public static void sortByNumber(Course[] list) {
Course temp = new Course();

boolean fixed = false;

while(fixed == false) {
fixed = true;
for (int i = 0; i<list.length-1; i++) {

if (list[i].getNum() > list[i+1].getNum()) {
temp.setNum(list[i].getNum());
temp.setDept(list[i].getDept());
temp.setTitle(list[i].getTitle());

list[i] = list[i+1];
list[i+1] = temp;
fixed = false;
}
}
}}

这是一种对大学提供的类(class)进行排序的方法。

例如,每门类(class)都有其部门(即数学)、编号(即 263)和标题(即工程师常微分方程) - MATH 263 工程师常微分方程。

在我的另一个类中,我创建了一个对象 Course,它有自己的访问器和修改器(即 getNum()、setNum()、getDept() 等)。

给定一长串类(class),我想根据类(class)编号来排列它们,但上述方法似乎不起作用。

有人可以暗示一下原因吗?

最佳答案

temp 变量是对 Course 对象的引用。

实际上,数组list是对Course对象的引用的数组。

您只需更改引用,无需将对象的值复制到 temp 中。只需执行 temp = list[i]; 即可保留对数组第 i 个元素的引用。

关于java - 排序数组: Bubble sort,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34033542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com