帮我写一个java的冒泡排序
时间: 2023-03-01 15:05:47 浏览: 34
好的,这是一个简单的java实现的冒泡排序程序:
```
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
System.out.println("排序后的数组:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
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[] arr = {5, 1, 4, 2, 8};
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
// 交换位置
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
// 输出排序后的数组
for(int i=0; i < n; i++){
System.out.print(arr[i] + " ");
}
}
}
```
在这个例子中,我们使用了两个 for 循环来实现冒泡排序。外部循环控制排序的轮数,内部循环控制每一轮比较的次数。如果相邻的两个数大小不符合排序要求,就交换它们的位置。经过多轮比较和交换后,数组中的数字就可以按照从小到大的顺序排列。
希望这个例子能够帮助你理解冒泡排序的基本思想和实现过程。
帮我写一个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]) {
// 交换 arr[j] 和 arr[j+1]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
```
这个算法的时间复杂度是 O(n^2),它是一种稳定的排序算法。
相关推荐
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.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_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)