选择排序,冒泡排序,插入排序
程序员文章站
2022-07-02 14:21:17
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 }