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

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) {
        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;
                }
            }
        }
    }
}

运行结果为:2 3 4 5 8

冒泡排序法的基本思路是:重复遍历要排序的数列,每次遍历将相邻的两个元素进行比较,如果顺序不对则交换它们,直到整个数列都变得有序为止。

用java代码写冒泡排序法

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

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