Sorting: Bubble Sort

  • + 0 comments

    Java:

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