[英]Sorting Array: Bubble sort
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;
}
}
}}
This is a method for sorting courses offered by university. 这是一种对大学提供的课程进行排序的方法。
For example, each course has its department (ie MATH), number (ie 263) and title (ie Ordinary Differential Equations for Engineers) - MATH 263 Ordinary Differential Equations for Engineers. 例如,每个课程都有其系(即MATH),编号(即263)和标题(即工程师的常微分方程)-MATH 263工程师的常微分方程。
In my another class, I have created an object Course, which has its own accessors and mutators (ie getNum(), setNum(), getDept(), so on). 在另一个类中,我创建了一个对象Course,它具有自己的访问器和变量(即getNum(),setNum(),getDept()等)。
Given a long list of courses, I wanted to arrange them according to their course numbers, but the above method does not seem to work. 给定一长串的课程,我想根据课程的编号排列它们,但是以上方法似乎行不通。
Can someone hint reason for this? 有人可以暗示原因吗?
The temp
variable is a reference to a Course
object. temp
变量是对Course
对象的引用。
Actually the array list
is an array of references to Course
objects. 实际上,数组list
是对Course
对象的引用的数组。
You only need to change references and not copy the object's values into temp
. 您只需要更改引用,而无需将对象的值复制到temp
。 Just do temp = list[i];
只是做temp = list[i];
to keep a reference to the i-th element of the array. 保留对数组第i个元素的引用。
I would rather implement the Comparable
interface. 我宁愿实现Comparable
接口。
class Course implements Comparable<Course>{
@Override
public int compareTo(Course other){
return this.getNum().compareTo(other.gerNum());
}
}
And then you can use Array.sort(Course[] list)
to sort your courses array. 然后,您可以使用Array.sort(Course[] list)
对课程数组进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.