輸入一組長度一定的資料,從大到小(小到大)排序
阿新 • • 發佈:2022-12-03
簡單的排序題,課堂練習
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++) { 35if (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 }
效果如下: