请用Java语言写冒泡排序
时间: 2023-05-10 08:55:10 浏览: 66
当然可以,以下是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)。
相关问题
用java语言写冒泡排序
以下是Java语言实现冒泡排序的示例代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] array = {5, 3, 8, 4, 2};
bubbleSort(array);
for (int i : array) {
System.out.print(i + " ");
}
}
public static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
```
其中,`bubbleSort`方法实现了冒泡排序算法,它使用双重循环对数组中的元素进行比较和交换,从而实现排序。在`main`方法中,我们定义了一个整型数组,然后调用`bubbleSort`方法对其进行排序,并输出排序后的结果。
用Java语言写冒泡排序
以下是Java语言实现冒泡排序的示例代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] array = {5, 3, 8, 4, 2};
bubbleSort(array);
for (int i : array) {
System.out.print(i + " ");
}
}
public static void bubbleSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
```
其中,`bubbleSort`方法实现了冒泡排序算法,它使用双重循环对数组中的元素进行比较和交换,从而实现排序。在`main`方法中,我们定义了一个整型数组,然后调用`bubbleSort`方法对其进行排序,并输出排序后的结果。
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)