JetBrains Academy: Bubble sort in Java - Kamil-Jankowski/Learning-JAVA GitHub Wiki

JetBrains Academy: Bubble sort in Java

Swaps:

For a given array, using Bubble sorting, count the number of swaps (exchanges of two numbers) you need to do to fully sort the array in the ascending order. You need to output the number of swaps.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] input = Arrays.stream(scanner.nextLine().split("\\s+"))
                            .mapToInt(Integer::parseInt)
                            .toArray();
        
        int result = countSwaps(input);
        
        System.out.println(result);
    }
    
    public static int countSwaps(int[] array) {
        int count = 0;

        for (int i = 0; i < array.length - 1; i++) {
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    int localMin = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = localMin;
                    count++;    // count the swap
                }
            }
        }
        return count;
    }
}

Swaps 2:

For a given array, using Bubble sorting, count the number of swaps (exchanges of two numbers) you need to do to fully sort the array in the descending order. You need to output the number of swaps.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] input = Arrays.stream(scanner.nextLine().split("\\s+"))
                            .mapToInt(Integer::parseInt)
                            .toArray();
        
        int result = countSwaps(input);
        
        System.out.println(result);
    }
    
    public static int countSwaps(int[] array) {
        int count = 0;

        for (int i = 0; i < array.length - 1; i++) {
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] < array[j + 1]) {
                    int localMax = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = localMax;
                    count++;    // count the swap
                }
            }
        }
        return count;
    }
}