排序算法浅析——插入排序

来源:互联网 发布:淘宝没有展现词 编辑:程序博客网 时间:2024/06/08 05:58

插入排序

平时学的一些总容易忘,所以记录一下,加强记忆。本文主要介绍直接插入排序和希尔排序。

1、插入排序—直接插入排序(Straight Insertion Sort)

算法描述

》将一条记录插入到已排序好的有序表中,从而得到一个新的有序表,记录数增1的有序表。即:先将序列的第1个记录看成是一个有序的子序列,然后从第2个记录逐个进行插入,直至整个序列有序为止。
》要点:设立哨兵,作为临时存储和判断数组边界之用。
》具体过程如图所示:
这里写图片描述

算法分析

平均时间复杂度:O(n2)
空间复杂度:O(1) (用于记录需要插入的数据)
稳定性:稳定

算法实现

public class StraightInsertionSort {    public static int[] Straight(int[] sort) {        if (sort.length == 0) {            return sort;        }        for (int i = 1; i < sort.length; i++) {            int flagTemp = sort[i];            if (flagTemp > sort[i - 1]) {                continue;            }            int j = (i - 1);            while (j >= 0) {                if (sort[j] > flagTemp) {                    sort[j + 1] = sort[j];                } else {                    break;                }                j--;            }            sort[j + 1] = flagTemp;        }        return sort;    }    public static void main(String[] args) {        int[] test = { 3, 1, 5, 7, 2, 4, 9, 6 };        int[] test2 = StraightInsertionSort.Straight(test);        for (int result : test2) {            System.out.print(result + " ");        }    }}

2、插入排序—希尔排序(Shell`s Sort)

算法描述

》把整个待排序的记录按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。
》具体过程如图所示:
这里写图片描述

算法分析

平均时间复杂度:O(Nlog2N)(取决于增量的选取,优于直接插入排序)
空间复杂度:O(1)
稳定性:不稳定

算法实现

其中增量dk直接初始为序列长度的一半,并不停的缩小为dk/2,步长的选择是希尔排序的重要部分。只要最终步长为1任何步长序列都可以工作,并且选取不同的步长也关系着时间复杂度,这里我只简单的实现,想了解步长的选择可以查看其它资料。

public class ShellSort {    public static int[] shell(int[] sort){        int dk = sort.length / 2;        while(dk >= 1){            for(int i=0; i<sort.length - dk; i++){                if(sort[i] > sort[i+dk]){                    int temp = sort[i];                    sort[i] = sort[i+dk];                    sort[i+dk] = temp;                }            }            dk = dk / 2;        }        return sort;    }    public static void main(String[] args) {        int[] test = { 3, 1, 5, 7, 2, 4, 9, 6 };        int[] test2 = ShellSort.shell(test);        for (int result : test2) {            System.out.print(result + " ");        }    }}

参考:
http://www.cnblogs.com/jingmoxukong/p/4303279.html
http://blog.csdn.net/hguisu/article/details/7776068

0 0
原创粉丝点击