输入一组长度一定的数据,从大到小(小到大)排序

简单的排序题,课堂练习

 1 import java.util.Scanner;
 2 
 3 public class Animal {
 4 
 5 
 6     public static void main(String[] args) {
 8         Scanner scanner = new Scanner(System.in);
 9         int[] a = new int[10];
10         for (int i = 0; i < a.length; i++) {
11             a[i] = scanner.nextInt();
12         }
13 
14 
15         int temp;
16         for (int i = 0; i < a.length - 1; i++) {
17             for (int j = 0; j < a.length - i - 1; j++) {
18                 if (a[j] < a[j + 1]) {
19                     temp = a[j];
20                     a[j] = a[j + 1];
21                     a[j + 1] = temp;
22                 }
23             }
24         }
25         for (int i : a) {
26             System.out.print(i + " ");
27         }
28 
29 
30         System.out.println();
31 
32 
33         for (int i = 0; i < a.length - 1; i++) {
34             for (int j = 0; j < a.length - i - 1; j++) {
35                 if (a[j] > a[j + 1]) {
36                     temp = a[j];
37                     a[j] = a[j + 1];
38                     a[j + 1] = temp;
39                 }
40             }
41         }
42         for (int i : a) {
43             System.out.print(i + " ");
44         }
45     }
46 }

效果如下:

 

posted @ 2022-12-03 17:33  ViolentYfTy  阅读(37)  评论(0)    收藏  举报