public class Test17 { public static void main(String[] args) { int []arr = new int[5]; for (int x = 1; x < 100; x++) { Random r = new Random(); arr[0] = r.nextInt(x); arr[1] = r.nextInt(x); arr[2] = r.nextInt(x); arr[3] = r.nextInt(x); arr[4] = r.nextInt(x); } printArray(arr); maopaoSort(arr); System.out.println("\n"); printArray(arr); selectSort(arr); System.out.println("\n"); printArray(arr); } private static void selectSort(int[] arr) { for (int i = 0; i < arr.length-1; i++) { for (int j = i+1; j < arr.length; j++) { if(arr[i]>arr[j]) swap(arr,i,j); } } } private static void maopaoSort(int[] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length-1; j++) { if(arr[j]>arr[j+1]) swap(arr,j,j+1); } } } private static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i]=arr[j]; arr[j]=temp; } public static void printArray(int []arr){ for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]+" "); } } }
时间: 2024-12-18 01:59:14