用java写一个冒泡算法
时间: 2024-01-04 13:04:49 浏览: 18
以下是用 Java 实现冒泡排序的代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 3, 9, 1};
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++) {
boolean flag = false; // 用来标记是否有交换
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;
flag = true;
}
}
if (!flag) {
break; // 如果没有交换,说明已经有序,可以直接退出循环
}
}
}
}
```
注:冒泡排序的基本思想是,每次比较相邻的两个元素,如果顺序不对就交换,一轮比较下来可以将最大的元素放到最后,然后对剩下的元素再进行比较,直到所有元素都有序。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)