代码
public class InsertSort {
static int[] arr = {6,7,0,-5,8,1,3,2};
public static void main(String[] args) {
System.out.println("排序前:" +Arrays.toString(arr));
insertSort();
System.out.println("排序后:" +Arrays.toString(arr));
}
protected static void insertSort() {
for (int i = 1; i < arr.length; i++) {
//定义待插入的数
int insertVal = arr[i];
//即arr[1]前面这个数的下标
int insertIndex = i - 1;
while(insertIndex >= 0 && insertVal < arr[insertIndex]){
//arr[insertIndex] 后移
arr[insertIndex + 1] = arr[insertIndex];
insertIndex --;
}
if(insertIndex + 1 != i){
arr[insertIndex + 1] = insertVal;
}
System.out.println("第" + i + "轮结果是:" + Arrays.toString(arr));
}
}
}
结果
性能(8万个随机数排序)
大概是2s多一点