Sorting: Bubble Sort

  • + 0 comments

    JAVA 8

    public static void countSwaps(List<Integer> a) {
            int count = 0;
            for (int i = 0; i < a.size(); i++) {
                for (int j = 0; j < a.size() - 1; j++) {
                    if (a.get(j) > a.get(j + 1)) {
                        int aux = a.get(j);
                        a.set(j, a.get(j + 1));
                        a.set(j + 1, aux);
                        count++;
                    }
                }
            }
            System.out.println("Array is sorted in " + count + " swaps.");
            System.out.println("First Element: " + a.get(0));
            System.out.println("Last Element: " + a.get(a.size() - 1));
        }