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

public class BubbleSort {
    public static void main(String[] args) {
        int[] arr = {5, 2, 6, 1, 3, 9, 4};
        bubbleSort(arr);
        System.out.println(Arrays.toString(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]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
}

该代码使用两层循环,外层循环控制排序轮数,内层循环控制每轮比较的次数。在每轮比较中,如果相邻两个元素的顺序不正确,则交换它们的位置。最终达到将数组按从小到大的顺序排序的目的。


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

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