zoukankan      html  css  js  c++  java
  • 排序算法之直接插入排序

    直接插入排序:顺序的将待排序的数据对象按其值得大小插入到已排序数据元素的有序序列的适当位置。有序序列的数据元素从只有一个数据元素之间增加到所有的素具元素,排序结束。分为倒序比较和正序比较,以下是顺序比较的例子:

    //直接插入排序
    
    const NumberArr = [1, 2, 3, 6, 3, 2, 88, 32, 76, 23, 2, 1];
    
    /**
     * 升幂,倒序比较
     * @param {*} arr 
     */
    function insert_sort_asc(arr) {
        let temp = 0;
        for (let i = 1; i < arr.length; i++) {
            temp = arr[i];
            let j;
            for (j = i; j > 0 && temp < arr[j - 1]; j--) {
                arr[j] = arr[j - 1]; //将大的往有序序列后挪
            }
            arr[j] = temp; //插入到合适位置
        }
        return arr;
    }
    
    /**
     * 降幂 倒序比较
     * @param {*} arr 
     */
    function insert_sort_desc(arr) {
        let temp = 0;
        for (let i = 1; i < arr.length; i++) {
            temp = arr[i];
            let j;
            for (j = i; j > 0 && temp > arr[j - 1]; j--) {
                arr[j] = arr[j - 1]; //将小的往有序序列后挪
            }
            arr[j] = temp; //插入到合适位置
        }
    
        return arr;
    }
    
    /**
     * 正序比较需要挪动太多的元素
     */
    
    console.log(insert_sort_desc(NumberArr));

    算法简洁,但是只有待排序元素个数n较少时,效率才高。

    所需空间:一个表示当前元素的哨兵nTemp。

    所需时间:主要与所需关键字的比较次数和移动的次数有关。

    最坏情况——逆序:总的比较次数为n(n-1)/2,记录的移动次数也为n(n-1)/2,时间复杂度O(n^2)。

    最好情况——正序:比较次数为n-1,记录移动次数为0,时间咋读O(n)。

    由此可推算出直接插入排序算法的平均时间为O(n^2)。

  • 相关阅读:
    MyEclipse中配置Hibernate
    struts2_对Map进行双层迭代
    Hibernate关联关系全集
    CodeIgniter+Smarty配置
    去掉php框架CI默认url中的index.php【整理】
    jquery的show方法是display:block还是display:inline呢?
    Codeigniter中的Error【转】
    去除 inlineblock 空隙终极解决方案
    jquery三级折叠菜单
    css实现页面文字不换行、自动换行、强制换行
  • 原文地址:https://www.cnblogs.com/huanqiuxuexiji/p/9164572.html
Copyright © 2011-2022 走看看