冒泡排序使用Java 怎么写
时间: 2023-05-11 10:05:45 浏览: 27
冒泡排序的Java代码如下:
```
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]) {
// swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
```
这段代码实现了冒泡排序,它可以对一个整数数组进行排序。
相关问题
写一个冒泡排序使用JAVA
好的,下面是一个使用Java实现的冒泡排序的代码示例:
```java
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;
}
}
}
}
```
使用方法:
```java
int[] arr = {5, 2, 7, 3, 1};
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
```
输出结果:
```
[1, 2, 3, 5, 7]
```
希望这个示例可以帮助你更好地理解冒泡排序的实现过程。
使用Java写冒泡排序
可以的,冒泡排序是一种简单的排序算法,使用Java语言实现也比较容易。以下是一个Java实现的冒泡排序代码示例:
```
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;
}
}
}
}
```
这段代码实现了对一个整型数组进行冒泡排序,时间复杂度为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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)