# Java 程序：升序和降序的冒泡排序

> 原文： [https://beginnersbook.com/2014/07/java-program-for-bubble-sort-in-ascending-descending-order/](https://beginnersbook.com/2014/07/java-program-for-bubble-sort-in-ascending-descending-order/)

在本教程中，我们将看到如何在按升序和降序进行排序。使用[冒泡排序](https://en.wikipedia.org/wiki/Bubble_sort)算法降序排序。

## 冒泡排序程序，按升序排序

```java
import java.util.Scanner;

class BubbleSortExample {
  public static void main(String []args) {
    int num, i, j, temp;
    Scanner input = new Scanner(System.in);

    System.out.println("Enter the number of integers to sort:");
    num = input.nextInt();

    int array[] = new int[num];

    System.out.println("Enter " + num + " integers: ");

    for (i = 0; i < num; i++) 
      array[i] = input.nextInt();

    for (i = 0; i < ( num - 1 ); i++) {
      for (j = 0; j < num - i - 1; j++) {
        if (array[j] > array[j+1]) 
        {
           temp = array[j];
           array[j] = array[j+1];
           array[j+1] = temp;
        }
      }
    }

    System.out.println("Sorted list of integers:");

    for (i = 0; i < num; i++) 
      System.out.println(array[i]);
  }
}
```

**输出：**

```java
Enter the number of integers to sort:
6
Enter 6 integers: 
12
6
78
9
45
08
Sorted list of integers:
6
8
9
12
45
78

```

## 冒泡排序程序，按降序排序

为了按降序排序，我们只需要将上面程序中的数组`array`的逻辑从`array[j] > array[j+1]`更改为`array[j] < array[j+1]`。完整代码如下：

```java
import java.util.Scanner;

class BubbleSortExample {
  public static void main(String []args) {
    int num, i, j, temp;
    Scanner input = new Scanner(System.in);

    System.out.println("Enter the number of integers to sort:");
    num = input.nextInt();

    int array[] = new int[num];

    System.out.println("Enter " + num + " integers: ");

    for (i = 0; i < num; i++) 
      array[i] = input.nextInt();

    for (i = 0; i < ( num - 1 ); i++) {
      for (j = 0; j < num - i - 1; j++) {
        if (array[j] < array[j+1]) 
        {
          temp = array[j];
          array[j] = array[j+1];
          array[j+1] = temp;
        }
      }
    }

    System.out.println("Sorted list of integers:");

    for (i = 0; i < num; i++) 
      System.out.println(array[i]);
  } 
}
```

**输出：**

```java
Enter the number of integers to sort:
6
Enter 6 integers: 
89
12
45
9
56
102
Sorted list of integers:
102
89
56
45
12
9
```