帮我写一个 冒泡排序 java
时间: 2023-10-18 14:15:50 浏览: 37
当然可以,以下是 Java 冒泡排序的实现:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {3, 1, 4, 2, 5};
bubbleSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
public static void bubbleSort(int[] arr) {
int len = arr.length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
代码解释:
- 外层循环控制排序轮数,排序轮数为数组长度减一。
- 内层循环控制比较和交换,每次比较相邻两个元素的大小,如果前一个元素大于后一个元素,则交换两个元素的位置。
- 时间复杂度为 O(n^2),不适合对大规模数据进行排序。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)