public class BubbleSort { public static void main(String[] args) { int[] arr = {5, 3, 8, 4, 2}; bubbleSort(arr); for (int i : arr) { System.out.print(i + ' '); } }

public static void bubbleSort(int[] arr) {
    for (int i = 0; i < arr.length - 1; i++) {
        for (int j = 0; j < arr.length - 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;
}

}

Java 冒泡排序算法实现:步骤详解和代码示例

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

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