Java Bubblesort Algorithm

笑着哭i 提交于 2020-01-16 09:36:33

问题


I am trying to use the summer to practice more Java to get better by learning how to code algorithms. I have this problem where I add elements to my ArrayList but somehow the first number I add also sets the number of positions in my list which I want to avoid. I only want the 0th index to contain the number 5. I seem to not catch a clue on how to solve this.

public class Algorithms {

private ArrayList<Integer> numbers;

public Algorithms() {

    numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(4);
    bubblesort();
}

public static void main(String args[]) {
    new Algorithms();
}

public void bubblesort() {

    System.out.println(numbers);
    for (int a = 0; a < numbers.size();) {
        for (int b = 1; b < numbers.size();) {
            int currentNumber = numbers.get(a);
            if (currentNumber > numbers.get(b)) {

                //Collections.swap(numbers, currentNumber, numbers.get(b));

                numbers.set(numbers.get(a), numbers.get(b));
                numbers.set(numbers.get(b), numbers.get(a));

                a++;
                b++;

            } else if (currentNumber < numbers.get(b)) {
                a++;
                b++;
            }
            System.out.println(numbers);
        }
    }
}
}

回答1:


You are not swapping elements correctly. Instead of

numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));

it should be

int temp = numbers.get(a);
numbers.set(a, numbers.get(b));
numbers.set(b, temp);



回答2:


The below two statements:

numbers.set(numbers.get(a), numbers.get(b));
numbers.set(numbers.get(b), numbers.get(a));

is not performing swapping. The first argument to the List#set(int, E) method is the index in the list, where you want to set the value passed as 2nd argument. You need to use a temp variable for swapping.

Also, the swapping didn't work for your commented line for the same reason. Collections#swap method take indices for swapping. So, just change:

Collections.swap(numbers, currentNumber, numbers.get(b));

to:

Collections.swap(numbers, a, b);

And please for the love of all that is holy, don't call method from inside a constructor. Remove the method invocation from inside the constructor, and move it to main method like this:

Algorithms algo = new Algorithms();
algo.bubbleSort()


来源:https://stackoverflow.com/questions/18561618/java-bubblesort-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!