user8439132
user8439132

Reputation: 3

Write a Method that Sorts an ArrayList of Numbers

From Liang's Intro to Java Programming (10th edition):

Exercise 13.3: Write the following method that sorts an ArrayList of numbers.

public static void sort(ArrayList<Number> list)

My code:

public static void sort(ArrayList<Number> list) {

    Number temp = 0;

    for (int i = 0; i < list.size() - 1; i++) {
        for (int j = 1; j < list.size(); j++) {
            if (list.get(j).doubleValue() < list.get(i).doubleValue()) {
                temp = list.get(i);
                list.set(i, list.get(j));
                list.set(j, temp);
            }
        }
    }
}

In the main method I instantiated an ArrayList of Numbers and some arbitrary values: [7, 1, 3.14, -5, 2, 5.187, 9, 6.6667, 4.1]

My output after using my sort method: [-5, 9, 7, 6.6667, 5.187, 3.14, 2, 1, 4.1] (which is clearly incorrect).

It's pretty late and I'm having trouble figuring out exactly what I did wrong for this problem. If anyone could point out the logical errors that I made it would help save a lot of time. Thanks!

Upvotes: 0

Views: 1752

Answers (3)

Ali Faris
Ali Faris

Reputation: 18592

you should make the nested loop starts from i+1 not from 1

for (int i = 0; i < list.size() - 1; i++) {
    for (int j = i+1; j < list.size(); j++) {
    ...
    }
}

Upvotes: 0

Thomas B&#246;hm
Thomas B&#246;hm

Reputation: 1486

Your problem is, that you start the second loop with 0 every time. That means, that you also take the already-ordered elements.

Change your second loop to for (int j = i+1..., so you start the inner loop with the unsorted rest of the list (the elements that should really be compared to the one at index i).

Upvotes: 0

Brijesh Shah
Brijesh Shah

Reputation: 172

This should do it:

public static void sort(ArrayList<Number> list) {

Number temp = 0;

for (int i = 0; i < list.size() - 1; i++) {
    for (int j = i+1; j < list.size(); j++) {
        if (list.get(j).doubleValue() < list.get(i).doubleValue()) {
            temp = list.get(i);
            list.set(i, list.get(j));
            list.set(j, temp);
        }
    }
}
}

Upvotes: 3

Related Questions