zoukankan      html  css  js  c++  java
  • 插入排序及时间复杂度的计算

    插入排序算法:
    def insertSort(listx):
        n=len(listx)
        for i in range(1,n):
            key=listx[i]
            j=i-1
            while j>0:
                if listx[j]>key:
                    listx[j+1]=listx[j]
                    listx[j]=key
                    j-=1
                else:
                    break
        print listx
    时间复杂度:
    O(1)<....
    然后我们计算上一期冒泡排序的时间复杂度:
    1:n-1
    2:n-2
    3:n-3
    4:n-4
    .
    .
    .n-1:1
    (n-1+1)(n-1)/2=(n^2-n)/2=n^2/2-n/2
    因为n/2相对于n^2在大数据排序分析上可以忽略不计,我们只考虑影响最大的因素,所以时间复杂度结果就为:O(n^2)
    插入排序的时间复杂度:
    最好情况(刚好是按照预期有序数据进行排序):
    所以结果就是:n-1
    最坏情况:
    1:n-1
    2:n-2
    3:n-3
    4:n-4
    .
    .
    .n-1:1
    (n-1+1)(n-1)/2=(n^2-n)/2
    所以平均复杂度为:
    ((n^2-n)/2+n-1)/2=n^2/4-n/4+n/2-1/2=n^2/4+n/2-1/2
    同理,插入排序结果影响时间复杂度最大的因子仍然是n^2,所以最终的时间复杂度仍然是:O(n^2)

  • 相关阅读:
    python+selenium初学者常见问题处理
    pycharm的这些配置,你都知道吗
    巧用浏览器F12调试器定位系统前后端bug
    dsu + lca
    indeed2017校招在线编程题(网测)三
    rolling hash
    ac自动机
    indeed 第二次笔试题
    vmware以及schlumberger题解
    2017 google Round C APAC Test 题解
  • 原文地址:https://www.cnblogs.com/zhangtebie/p/11185874.html
Copyright © 2011-2022 走看看