gymcode
gymcode

Reputation: 4633

BubbleSort troubleshooting

It is my first attempt to do sorting in arrays. I am looking in BubbleSort. I looked up many examples on the net. However, I could not get my bubble sort working. Below is a snippet of my code:

//Sort by StudentID (long variable)

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  
                    }
                }

            }
        }
    }
}

//My main method

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

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

                        studentList[i].writeOutput();

                    }

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

Upvotes: 0

Views: 144

Answers (1)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26946

You have to swap elements. Your code doesn't. In addition you have to check if you had modifications in your for loop. If yes you have to repeat the procedure.

So change it as follow

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);
    }
}

Upvotes: 1

Related Questions