冒泡排序故障排除

BubbleSort troubleshooting

这是我第一次尝试对数组进行排序。我正在寻找 BubbleSort。我在网上查了很多例子。但是,我无法让我的冒泡排序工作。下面是我的代码片段:

//按学号排序(长变量)

public static void BubbleSort(Student[] st) {
    long tempID;   //holding variable

    for (int j = 0; j < st.length - 1; j++) {
        if (st[j] != null) {
            long studentID1 = st[j].getStudentID();
            if (st[j + 1] != null) {
                long studentID2 = st[j + 1].getStudentID();
                if ((st[j] != null) && (st[j + 1] != null)) {
                    if (studentID1 < studentID2) // change to > for ascending sort
                    {
                        tempID = studentID1;                //swap elements
                        studentID1 = studentID2;
                        studentID2 = tempID;             //shows a swap occurred  
                    }
                }

            }
        }
    }
}

//我的主要方法

if (studentIndex >= 0) {
                    BubbleSort(studentList);

                    for (int i = 0; i <= studentIndex; i++) {

                        studentList[i].writeOutput();

                    }

                } else {
                    System.out.println("No sorting done");
                }

你必须交换元素。你的代码没有。 此外,您必须检查您的 for 循环中是否有修改。如果是,则必须重复该过程。

所以修改如下

public static BubbleSort(Student[] st) {

    Student temp;   //holding variable
    boolean changed = false;
    for (int j = 0; j < st.length - 1; j++) {
        if (st[j] != null) {
            long studentID1 = st[j].getStudentID();
            if (st[j + 1] != null) {
                long studentID2 = st[j + 1].getStudentID();
                if ((st[j] != null) && (st[j + 1] != null)) {
                    if (studentID1 < studentID2) // change to > for ascending sort
                    {
                        temp = st[j];  //swap elements
                        st[j] = st[j + 1];
                        st[j + 1] = temp;  //shows a swap occurred  
                        changed = true; 
                     }                   
                }
            }

        }
    }
    if (changed) {
        BubbleSort(st);
    }
}