以下是Java实现冒泡排序的代码:

public class BubbleSort {
    public static void bubbleSort(int[] array) {
        int n = array.length;
        for (int i = 0; i < n - 1; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    // 交换相邻两个元素的位置
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] array = {5, 2, 9, 4, 7, 6, 1, 3, 8};
        bubbleSort(array);
        System.out.println(Arrays.toString(array));
    }
}

输出结果为:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

冒泡排序的时间复杂度为O(n^2),不适用于大规模数据的排序。

java 实现冒泡排序

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

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