java实现冒泡算法
时间: 2023-08-16 07:04:21 浏览: 41
冒泡排序是一种简单的排序算法,它的基本思想是依次比较相邻的两个数,如果顺序错误就交换位置,直到没有相邻的数需要交换为止。以下是用 Java 实现冒泡排序的示例代码:
```java
public class BubbleSort {
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;
}
}
}
}
public static void main(String[] args) {
int[] arr = {5, 2, 8, 7, 1, 3, 9, 6};
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
}
```
在上面的代码中,我们定义了一个 `bubbleSort` 方法,它接受一个整数数组作为参数,然后根据冒泡排序算法对数组进行排序。在 `main` 方法中,我们创建了一个测试数组,并调用 `bubbleSort` 方法对其进行排序。最后,我们使用 `Arrays.toString` 方法将排序后的数组打印出来。