- 代码
public class InsertSort {
public static void main(String[] args) {
int array[] = {6,5,8,19,60,25,54,7,3,10,22};
insertSort(array);
System.out.println(Arrays.toString(array));
}
private static void insertSort(int[] array) {
for (int i = 1; i < array.length; i++) {//从数组第二个开始设置暂存元素
int insetValue = array[i];//暂存元素
int j = i - 1;//暂存元素前一个元素
//嵌套循环(内循环),即针对暂存元素进行循环
for (; j >= 0 && insetValue < array[j] ; j--) {//从右向左比较元素的同时,进行元素的复制,j--导致j向前移动了一位
array[j+1] = array[j];//复制元素到下一个位置
}
array[j+1] = insetValue;//暂存元素插入适当位置,又去for循环j--的原因,所以位置暂存元素位置为j+1
}
}
}