思路:
步骤:
代码:
package constxiong.interview.algorithm;
/**
* 插入排序
* @author ConstXiong
* @date 2020-04-08 09:35:40
*/
public class InsertionSort {
public static void main(String[] args) {
int [] array = {33, 22, 1, 4, 25, 88, 71, 4};
insertionSort(array);
}
/**
* 插入排序
*/
private static void insertionSort(int[] array) {
print(array);
for (int i = 1; i <array.length; i++) {
int j = i - 1;
int value = array[i];
for (; j >= 0; j--) {
if (array[j] > value) {
array[j+1] = array[j];
} else {
break;
}
}
array[j+1] = value;
print(array);
}
}
/**
* 打印数组
* @param array
*/
private static void print(int[] array) {
for(int i : array) {
System.out.print(i + " ");
}
System.out.println();
}
}
打印:
33 22 1 4 25 88 71 4
22 33 1 4 25 88 71 4
1 22 33 4 25 88 71 4
1 4 22 33 25 88 71 4
1 4 22 25 33 88 71 4
1 4 22 25 33 88 71 4
1 4 22 25 33 71 88 4
1 4 4 22 25 33 71 88
特征: