插入排序Insertion Sort

一、插入排序的基本思想

每次将一个待排序的数,插入到一个已排好序的子集合中,直到集合中所有的数都排好序。

集合S = {S0, S1, ... , Sn-1}

1、子集合 S'是一个有序集合,即是说S'中的数都是已经排好序的,待排序的数设置Si,

     开始时S' = {S0} 只有一个数,所以它是有序的集合, i = 1,待排序的数从S1开始;

2、将Si 插入到子集合 S' 中,并将S'排序好序,使得S'是有序集合;

3、i 的值加1,执行第2步,直到i 的值 等于 n-1,即最后一个Sn-1也插入了有序集合S'中,排序结束。


例如:

S = [2, 7, 3, 6, 5, 1]


开始时,设置有序集合是[2]:

[2, 7, 3, 6, 5, 1]


第1次,7是待排序的数,把7插入到有序集合[2]:

[2, 7, 3, 6, 5, 1]

则有序变成[2, 7]


第2次,3是待排序的数,把3插入到有序集合[2, 7]:

[2, 3, 7, 6, 5, 1]

则有序变成[2, 3, 7]


第3次,6是待排序的数,把6插入到有序集合[2, 3, 7]:

[2, 3, 6, 7, 5, 1]

则有序变成[2, 3, 6, 7]


第4次,5是待排序的数,把5插入到有序集合[2, 3, 6, 7]:

[2, 3, 5, 6, 7, 1]

则有序变成[2, 3, 5, 6, 7]


第5次,1是待排序的数,把1插入到有序集合[2, 3, 5, 6, 7]:

[1, 2, 3, 5, 6, 7]

则有序变成[1, 2, 3, 5, 6, 7]


集合S的数已经全部插入有序集合中,排序结束。


二、插入排序的java实现

public class InsertionSort {
    
    public static void sort(int[] ints){
        int lastIndex = ints.length -1;
        for(int firstIndex = 1; firstIndex <= lastIndex; firstIndex++){
            sort(ints, 0, firstIndex);
        }
    }
    
    /**
     * 有序集合:S' = { ints[fromIndex], ... , ints[targetIndex - 1] }
     * ints[targetIndex]:待排序的数
     * */
    public static void sort(int[] ints, int fromIndex, int targetIndex){
        //fromIndex to (targetIndex - 1) has sorted. 
        while(fromIndex < targetIndex){
            if(ints[fromIndex] >= ints[targetIndex]){
                int immutable = ints[targetIndex];
                //找到ints[targetIndex]应该所在的位置,
                //则将fromIndex, ..., targetIndex - 1, 移到 fromIndex + 1, ..., targetIndex
                move(ints, fromIndex, targetIndex);
                ints[fromIndex] = immutable;
                break;
            }
            fromIndex++;
        }
    }
    
    /**
     * 将下标位置在fromIndex, ..., toIndex - 1的数, 移到 fromIndex + 1, ..., toIndex
     * */
    private static void move(int[] ints, int fromIndex, int toIndex){
        while(fromIndex < toIndex){
            ints[toIndex] = ints[--toIndex];
        }
    }
    
    public static void main(String[] args){
        int[] ints = {2, 7, 3, 6, 5, 1};
        System.out.println(Arrays.toString(ints));
        
        sort(ints);
        System.out.println(Arrays.toString(ints));
    }

}


...

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值