前面的数比要插入的数值大,就往后移动。j >=0&& arr[j]>tmp 这个条件来控制内循环,保证插入的位置正确
import java.util.Arrays;
public class insert {
public static void main(String[] args) {
int[] arr={9,8,7,4,5,6,1,3,2};
sort(arr);
}
public static void sort(int[] arr) {
for (int i = 1; i <arr.length ; i++) {
int tmp=arr[i];
int j;
//j >=0&& arr[j]>tmp 这个判断是为了防止要插入的数比前面的大,消耗j,而插错位置
//比如执行到了第4轮时,arr为[4, 7, 8, 9, 5, 6, 1, 3, 2]。
//如果不加arr[j]>tmp的判断,
//进入内层的for,让j=-1,最后会变成[5, 7, 7, 8, 9, 6, 1, 3, 2]
for (j = i-1; j >=0&& arr[j]>tmp ; --j) {
//如果前面的数比要插入的数值大,就往后移动
arr[j+1]=arr[j];
}
arr[j+1]=tmp;
System.out.print(Arrays.toString(arr));
System.out.println();
}
}
}