package class01; import java.util.Arrays; /** * 插入排序 * 概述:先将i指向第二个数(索引为1),将j指向i-1位置,如果j大于等于0,并且arr[j]>arr[j+1],将将arr[j]和arr[j+1]交换。j--。 */ public class Code03_InsertSort { public static void insertSort(int[] arr) { if (arr == null || arr.length < 2) { return; } for (int i = 1; i < arr.length; i++) {//i直接从索引为1的位置,即第二个数字开始。 for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) { swap(arr, j, j + 1); } } } public static void swap(int[] arr, int i, int j) { arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } public static void printArr(int[] arr) { for (int i : arr) { System.out.print(i + " "); } System.out.println(); } public static int[] generateRandomArr(int maxSize, int maxValue) { int[] arr = new int[(int) (Math.random() * maxSize)]; for (int i = 0; i < arr.length; i++) { arr[i] = (int) (Math.random() * maxValue); } return arr; } public static int[] copyArr(int[] arr1) { int[] arr2 = new int[arr1.length]; for (int i = 0; i < arr1.length; i++) { arr2[i] = arr1[i]; } return arr2; } public static void main(String[] args) { int maxSize = 10; int maxValue = 100; int testTimes = 10; boolean flag = true; for (int i = 0; i < testTimes; i++) { int[] arr1 = generateRandomArr(maxSize, maxValue); int[] arr2 = copyArr(arr1); int[] arr3 = copyArr(arr1); Arrays.sort(arr2); insertSort(arr1); if (!isEquals(arr1, arr2)) { flag = false; System.out.println("oops!"); System.out.println("arr1 = " + Arrays.toString(arr1));//自己实现的冒泡排序。 System.out.println("arr2 = " + Arrays.toString(arr2));//工具类排好序的。 System.out.println("arr3 = " + Arrays.toString(arr3));//原数组,还没有排序。 break; } } System.out.println(flag ? "nice!" : "oops!"); int[] arr = generateRandomArr(maxSize, maxValue); printArr(arr); insertSort(arr); printArr(arr); } private static boolean isEquals(int[] arr1, int[] arr2) { if (arr1 == null && arr2 != null) { return false; } if (arr2 == null && arr1 != null) { return false; } if (arr1 == null && arr2 == null) { return true; } if (arr1.length != arr2.length) { return false; } for (int i = 0; i < arr1.length; i++) { if (arr1[i] != arr2[i]) { return false; } } return true; } }
标签:arr,return,int,插入排序,length,arr2,arr1 From: https://www.cnblogs.com/TheFloorIsNotTooHot/p/16838635.html