用java 写一个冒泡拍寻
时间: 2023-08-31 21:38:55 浏览: 57
### 回答1:
可以的,以下是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 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;
}
}
}
}
}
```
这段代码可以对数组进行冒泡排序,将数组中的元素按照从小到大的顺序排列。
### 回答2:
冒泡排序是一种简单的排序算法,通过多次比较和交换相邻元素的方式,将大的元素逐步“冒泡”到数组的末尾。以下是用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, 2, 9, 1, 3};
bubbleSort(arr);
System.out.println("排序结果:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```
在这个例子中,我们定义了一个名为`bubbleSort`的方法,通过两重循环进行比较和交换。外层循环控制总共需要比较的轮数,每一轮把最大的元素“冒泡”到数组的末尾。内层循环依次比较相邻的元素,如果前一个元素比后一个元素大,则进行交换。最终得到的排序结果是从小到大排列。
运行这段代码,控制台输出的结果为:1 2 3 5 9,即按从小到大的顺序排列的结果。
冒泡排序算法的时间复杂度为O(n^2),虽然效率较低,但对于小规模的数组仍然具有一定的实用性。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)