0

I have an array of objects read in from a user into an arraylist, when I attempt to bubble sort this data based off of a String parameter the program experiences a runtime error and the code does not execute.

Resort temp;
    while (finished = true) {
        finished = false;
        for (int index = 0; index < numResorts - 1; index++) {
            String nam1 = resorts.get(index).getName();
            String nam2 = resorts.get(index + 1).getName();
            if (nam1.compareTo(nam2) > 0) {
                temp = resorts.get(index);
                resorts.set(index, resorts.get(index + 1));
                resorts.set(index + 1, temp);
                //resorts.get(index) = resorts.get(index + 1);
                //resorts.get(index + 1) = temp;
                finished = true;
            }
        }
    }

2 Answers 2

3

You notice that you have an infinite loop there? The following while loop:

while (finished = true)

... always execute infinitely, since the expression always evaluate to true, because of that assignment. This is the reason why you should not compare boolean values. Simply do:

while (finished)  // this is enough.
Sign up to request clarification or add additional context in comments.

Comments

0

Here is my solution:

List<Integer> sortedlists = new ArrayList<Integer>();
public List<Integer> sortBs(List<Integer> al) {
    sortedlists = al;
    for(Integer out = al.size()-1; out>1; out--) {
        for(Integer i = 0; i < out;i ++){
            int n = i+1;
            if(sortedlists.get(i) > sortedlists.get(n)) {
                Integer temp = sortedlists.get(i);
                sortedlists.set(i, sortedlists.get(n));
                sortedlists.set(n, temp);
            }
        }
    }

    return sortedlists;
}

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.