1 package class01;
2
3 import java.util.Arrays;
4
5 public class Code03_InsertionSort {
6
7 public static void insertionSort(int[] arr) {
8 if (arr == null || arr.length < 2) {
9 return;
10 }
11 for (int i = 1; i < arr.length; i++) {
12 for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) {
13 swap(arr, j, j + 1);
14 }
15 }
16 }
17
18 public static void swap(int[] arr, int i, int j) {
19 arr[i] = arr[i] ^ arr[j];
20 arr[j] = arr[i] ^ arr[j];
21 arr[i] = arr[i] ^ arr[j];
22 }
23
24 // for test
25 public static void comparator(int[] arr) {
26 Arrays.sort(arr);
27 }
28
29 // for test
30 public static int[] generateRandomArray(int maxSize, int maxValue) {
31 int[] arr = new int[(int) ((maxSize + 1) * Math.random())]; //长度随机
32 for (int i = 0; i < arr.length; i++) {
33 arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) (maxValue * Math.random());
34 }
35 return arr;
36 }
37
38 // for test
39 public static int[] copyArray(int[] arr) {
40 if (arr == null) {
41 return null;
42 }
43 int[] res = new int[arr.length];
44 for (int i = 0; i < arr.length; i++) {
45 res[i] = arr[i];
46 }
47 return res;
48 }
49
50 // for test
51 public static boolean isEqual(int[] arr1, int[] arr2) {
52 if ((arr1 == null && arr2 != null) || (arr1 != null && arr2 == null)) {
53 return false;
54 }
55 if (arr1 == null && arr2 == null) {
56 return true;
57 }
58 if (arr1.length != arr2.length) {
59 return false;
60 }
61 for (int i = 0; i < arr1.length; i++) {
62 if (arr1[i] != arr2[i]) {
63 return false;
64 }
65 }
66 return true;
67 }
68
69 // for test
70 public static void printArray(int[] arr) {
71 if (arr == null) {
72 return;
73 }
74 for (int i = 0; i < arr.length; i++) {
75 System.out.print(arr[i] + " ");
76 }
77 System.out.println();
78 }
79
80 // for test
81 public static void main(String[] args) {
82 int testTime = 500000;
83 int maxSize = 100;
84 int maxValue = 100;
85 boolean succeed = true;
86 for (int i = 0; i < testTime; i++) {
87 int[] arr1 = generateRandomArray(maxSize, maxValue);
88 int[] arr2 = copyArray(arr1);
89 insertionSort(arr1);
90 comparator(arr2);
91 if (!isEqual(arr1, arr2)) {
92 succeed = false;
93 break;
94 }
95 }
96 System.out.println(succeed ? "Nice!" : "Fucking fucked!");
97
98 int[] arr = generateRandomArray(maxSize, maxValue);
99 printArray(arr);
100 insertionSort(arr);
101 printArray(arr);
102 }
103
104
插入排序的本质:假如有5个数【3,2,4,1,6】第一次选择第1个和第2个数,也就是i=1;j=i-1(j=0)然后比较大小(arr[j] > arr[j + 1]; 前一个数和后一个比较),把小的放前面。之后i+1,也就是选择前三个数,再循环比较一遍,然后继续i+1向前循环。最终比较完成!