1 public class Sort { 2 public static void main(String[] args) { 3 int[] arr = { 9, 54, 5, 47, 61, 2, 4, 32, 25 }; 4 selectSort(arr); 5 print(arr); 6 ... ...
1 public class Sort { 2 public static void main(String[] args) { 3 int[] arr = { 9, 54, 5, 47, 61, 2, 4, 32, 25 }; 4 selectSort(arr); 5 print(arr); 6 bubbleSort(arr); 7 print(arr); 8 int[] array = insertSort(arr); 9 print(array); 10 } 11 12 // 插入排序 13 public static int[] insertSort(int[] arr) { 14 for(int i = 0; i < arr.length; i++) { 15 for(int j = i; j > 0; j--) { 16 if(arr[j] < arr[j-1]) { 17 int temp = arr[j]; 18 arr[j] = arr[j-1]; 19 arr[j-1] = temp; 20 } 21 } 22 } 23 return arr; 24 } 25 26 //冒泡排序 27 public static void bubbleSort(int[] arr) { 28 for (int i = 0; i < arr.length; i++) { 29 for (int j = 0; j < arr.length - i - 1; j++) { 30 if(arr[j] > arr[j+1]) { 31 int temp = arr[j]; 32 arr[j] = arr[j+1]; 33 arr[j+1] = temp; 34 } 35 } 36 } 37 } 38 39 // 選擇排序 40 public static void selectSort(int[] arr) { 41 for (int i = 0; i < arr.length - 1; i++) { 42 for (int j = i + 1; j < arr.length; j++) { 43 if (arr[i] > arr[j]) { 44 int temp = arr[i]; 45 arr[i] = arr[j]; 46 arr[j] = temp; 47 } 48 } 49 } 50 } 51 52 public static void print(int[] arr) { 53 System.out.print("["); 54 for (int i = 0; i < arr.length; i++) { 55 if(i == arr.length-1) { 56 System.out.println(arr[i] + "]"); 57 }else { 58 System.out.print(arr[i] + ","); 59 } 60 } 61 } 62 }