插入排序实现(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public  class  InsertSort{
     
     public  void  insertSort( int [] array){
         for ( int  i= 1 ;i<array.length;i++) //第0位独自作为有序数列,从第1位开始向后遍历
         {
             if (array[i]<array[i- 1 ]) //0~i-1位为有序,若第i位小于i-1位,继续寻位并插入,否则认为0~i位也是有序的,忽略此次循环,相当于continue
             {
                 int  temp=array[i]; //保存第i位的值
                 int  k = i -  1 ;
                 for ( int  j=k;j>= 0  && temp<array[j];j--) //从第i-1位向前遍历并移位,直至找到小于第i位值停止
                 {
                     array[j+ 1 ]=array[j];
                     k--;
                 }
                 array[k+ 1 ]=temp; //插入第i位的值
             }
        
     }
     
     public  static  void  printArray( int [] array) {
           for  ( int  i =  0 ; i < array.length; i++) {
                System.out.print(array[i]);
                if  (i != array.length -  1 ) {
                 System.out.print( "," );
                }
           }
      }
 
     
 
}








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
using namespace std;
int  main()
{
     int  a[]={ 98 , 76 , 109 , 34 , 67 , 190 , 80 , 12 , 14 , 89 , 1 };
     int  k=sizeof(a)/sizeof(a[ 0 ]);
     int  j;
     for ( int  i= 1 ;i<k;i++) //循环从第2个元素开始
     {
         if (a[i]<a[i- 1 ])
         {
             int  temp=a[i];
             for (j=i- 1 ;j>= 0  && a[j]>temp;j--)
             {
                 a[j+ 1 ]=a[j];
             }
             a[j+ 1 ]=temp; //此处就是a[j+1]=temp;
         }
     }
     for ( int  f= 0 ;f<k;f++)
     {
         cout<<a[f]<< "  " ;
     }
     return  0 ;
}



从第二个元素开始,判断第二个元素的值与第一个元素的值是否有序,有则开始第三个数值continue。
没有序,认为前面的数值有序,现在,我们要将其插入到前面的有序数列,开始遍历前面的数值,插入正确的位置(开始第二个for循环)











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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值