用java实现冒泡排序
时间: 2023-01-29 11:43:52 浏览: 70
下面是用 Java 语言实现冒泡排序的代码示例:
```
public class BubbleSort {
public static void main(String[] args) {
// 测试数组
int[] arr = {6, 3, 8, 2, 9, 1};
// 打印原数组
System.out.println("原数组为:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
// 冒泡排序
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// 打印排序后的数组
System.out.println("排序后的数组为:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
运行结果:
```
原数组为:
6 3 8 2 9 1
排序后的数组为:
1 2 3 6 8 9
```
冒泡排序的基本思想是:
- 对于给定的一组数据,每次比较相邻两个数的大小,如果顺序不对就交换位置。
- 每次比较完成后,都能将最大(或最小)的数放到最后(或最前),因此经过多轮比较后,整个数组就变得有序了。
冒泡排序的时间复杂度为 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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![jpg](https://img-home.csdnimg.cn/images/20210720090814.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)