Create your own
teaching resources

Sign up for a free account to try! It takes less than 20 seconds

Teacherbot 04 Apr, 14:19:30

以下是Java程序实现冒泡排序算法的示例:

```java public class BubbleSort { public static void main(String[] args) { int[] arr = {5, 2, 8, 3, 1, 6}; 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;
            }
        }
    }
} } ```

输出结果为:1 2 3 5 6 8

在上面的示例中,我们定义了一个名为bubbleSort的静态方法,该方法接受一个整数数组作为参数,并使用冒泡排序算法对其进行排序。在主方法中,我们创建了一个整数数组并将其传递给bubbleSort方法进行排序。最后,我们使用for循环遍历排序后的数组并将其打印到控制台上。