//第1轮 {101,34,119,1 ==> {34,101,119,1}
int insertVal = arr[1];//定义待插入的数
int insertIndex = 1-1;//即arr[1]的前面这个数的索引
//给insertVal找到插入的位置
//说明:
//1.insertIndex >= 0 保证在给insertVal找插入位置时,不越界
//2.insertVal < arr[insertIndex] 待插入的数,还没找到插入位置
//3.需要将arr[insertIndex] 后移
while (insertIndex >= 0 && insertVal < arr[insertIndex]){
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
arr[insertIndex + 1] = insertVal;
System.out.println("第1轮排序:");
System.out.println(Arrays.toString(arr));
//第2轮 {34,101,119,1} ==> {34,101,119,1}
insertVal = arr[2];//定义待插入的数
insertIndex = 2-1;//即arr[1]的前面这个数的索引
while (insertIndex >= 0 && insertVal < arr[insertIndex]){
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
arr[insertIndex + 1] = insertVal;
System.out.println("第2轮排序:");
System.out.println(Arrays.toString(arr));
//第3轮 {34,101,119,1} ==> {1,34,101,119}
insertVal = arr[3];//定义待插入的数
insertIndex = 3-1;//即arr[1]的前面这个数的索引
while (insertIndex >= 0 && insertVal < arr[insertIndex]){
arr[insertIndex + 1] = arr[insertIndex];
insertIndex--;
}
arr[insertIndex + 1] = insertVal;
System.out.println("第3轮排序:");
System.out.println(Arrays.toString(arr));