0
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 (i.e. MATH), number (i.e. 263) and title (i.e. Ordinary Differential Equations for Engineers) - MATH 263 Ordinary Differential Equations for Engineers.

In my another class, I have created an object Course, which has its own accessors and mutators (i.e. getNum(), setNum(), getDept(), so on).

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?

2
  • arrange as in least to most, {100,101,102...201,202,...} Commented Dec 2, 2015 at 1:46
  • Hint: Look at your setters. You are not thinking in terms of object oriented programming. What was temp before you called its setters? What is it after? Commented Dec 2, 2015 at 1:52

2 Answers 2

3

The temp variable is a reference to a Course object.

Actually the array list is an array of references to Course objects.

You only need to change references and not copy the object's values into temp. Just do temp = list[i]; to keep a reference to the i-th element of the array.

Sign up to request clarification or add additional context in comments.

3 Comments

I see that my redundancy was inefficient, but why does it produce incorrect result?
You were pointing the i-th reference to the next object (the i+1-th one, that's OK), but made that i+1-th reference always point the temp object instead of pointing to the i-th object.
You can initialize the temp inside your loop which will be correct but THIS will be reduntant and inefficient. Pointing your temp to i+1 is the best solution. Check out the bubble sort algorithm on RosettaCode and some other sorting alternatives to learn. rosettacode.org/wiki/Sorting_algorithms/Bubble_sort#Java
0

I would rather implement the Comparable interface.

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.