用Java写一个冒泡排序
时间: 2023-05-25 19:00:56 浏览: 45
好的,以下是用 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, 4, 3, 2, 1};
bubbleSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
}
```
在这个代码中,我们定义了一个名为 `bubbleSort` 的静态方法,使用传入的整型数组 `arr` 进行冒泡排序。接下来我们在 `main` 方法中进行测试,将数组 `{5, 4, 3, 2, 1}` 传入 `bubbleSort` 方法中,排序之后打印出来。
运行以上代码,输出结果为:
```
1 2 3 4 5
```
以上就是用 Java 写的冒泡排序的代码,希望对你有帮助。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)