以下是Java语言的冒泡排序算法示例:

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

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

该算法的基本思想是:通过不断比较相邻两个元素的大小,将较大的元素向后移动,从而使整个序列逐步有序。在每一轮排序中,将最大的元素移到了序列的末尾,因此需要进行 n-1 轮排序,其中 n 表示序列的长度

用java编写一段冒泡代码

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

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