java冒泡排序从大到小从小到大哦
时间: 2024-01-02 12:22:59 浏览: 98
java 冒泡排序(从小到大)
5星 · 资源好评率100%
以下是Java中冒泡排序的实现,分别从大到小和从小到大排序:
1. 从大到小排序:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 2, 1};
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for ( 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;
}
}
}
System.out.println("从大到小排序结果:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
2. 从小到大排序:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 2, 1};
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;
}
}
}
System.out.println("从小到大排序结果:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
阅读全文