#GPT-4 Conversation #1097185078557298758

1 messages · Page 1 of 1 (latest)

olive geyserBOT
edgy fox
#

给个冒泡排序java代码

olive geyserBOT
# edgy fox 给个冒泡排序java代码

当然可以!这里有一个用Java实现的冒泡排序算法:

public class BubbleSort {
    public static void main(String[] args) {
        int[] arr = {5, 2, 8, 3, 6, 1};
        bubbleSort(arr);

        System.out.print("Sorted array: ");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }

    public static void bubbleSort(int[] arr) {
        int n = arr.length;
        boolean swapped;

        for (int i = 0; i < n - 1; i++) {
            swapped = false;
            for (int j = 0; j < n - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true;
                }
            }

            // 如果在一轮迭代中没有交换元素,那么数组已经排序完成
            if (!swapped) {
                break;
            }
        }
    }
}

这段代码实现了一个基本的冒泡排序算法。你可以根据需要调整或优化。希望这对你有帮助!

请注意,本次请求已消耗了一定数量的使用额度。要查看剩余额度,请输入/balance。如果额度不足,您可以通过访问 https://discord.gg/JCnxEaE3Mx 订阅以获得更多额度。

edgy fox
#

你好