杂记:进一步理解 插入排序

 int[] insert={1,534,63,23,75,204,56,99,6};
for(int i=0;i<insert.length-1;i++){
     int hand=i;
     int temp=insert[hand+1];
     while(hand>=0){//!!!!!
         if(temp<insert[hand]){
             insert[hand+1]=insert[hand];
             hand--;
         }
         else{
             break;
         }
         insert[hand+1]=temp;
     }
 }
        System.out.println(Arrays.toString(insert));
1,hand是要执行插入操作的元素的前一个元素的地址,temp是要执行插入操作的元素。

2,算法思想:将temp单独拎出来,与他前面的元素相比较,如果它小于前面的元素就将前元素覆盖到temp的地址上同时hand--,依次重复这个操作,直到条件不符合后跳出循环,最后将temp值赋值给地址hand+1 上,在whlie()循环过程中 temp 的值是固定的,hand 的值是变化的。

3,这个是打的一个while()循环的执行过程,便于理解:

无序数组:{1,2,31,345,20}
 1 2 31  345 20  hand==3  temp==20
 0 1  2   3  4 --->i

  hand==3    temp==20 (temp<345)需要插入操作
  1 2 31  345  345
  hand==2  temp==20  (temp<3131) 需要插入操作

  1 2  31 31 345
  hand==1  temp==20 !!!(temp>2)不用插入
    insert[2]<------hand+1 =temp

  1  2  20 31 345
  0  1   2  3   4---->i
 
[1, 6, 23, 56, 63, 75, 99, 204, 534]

Process finished with exit code 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值