JAVA冒泡排序
时间: 2023-06-28 18:08:33 浏览: 34
下面是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 len = arr.length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
这里使用了两层循环,外层循环控制排序的轮数,内层循环控制每一轮比较的次数。每次比较相邻两个元素的大小,如果前一个比后一个大,则交换它们的位置。通过多轮比较和交换,最终将序列中的元素按照从小到大的顺序排列。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)