public class BubbleSort { public static void main(String[] args) { int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5}; System.out.println('Before sorting:'); printArray(arr); bubbleSort(arr); System.out.println('After sorting:'); printArray(arr); }

public static void bubbleSort(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr, j, j+1);
            }
        }
    }
}

public static void swap(int[] arr, int i, int j) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

public static void printArray(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i] + " ");
    }
    System.out.println();
}

}


原文地址: https://www.cveoy.top/t/topic/mv2C 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录