算法导论 第一章 插入与归并排序

算法排序:input:sequence 《a1,a2,a3…..an》output: permutation 《a11,a22,a33,..ann》$ a110

 insertion sort


Insertioon-Sort(A,n) //Sorts A[1..n]    peusocode

for j<—2 to n

   do    key <—A[j]

           i<—j-1

            while i> 0 and A[i] > key

                 do A[i+1] <—A[i]

                 i<—i-1

   A[i+1]<—key


EX:[8,2,4,9,3,6]

start j = 2;

…..

[2,3,4,6,8,9]

Running time

—depends on input (e.g. already sorted)

—depends on input size (6 elem vs 6*10^9)

—parameter in input size

—Want upper bounds

Kinds of analysis

Worst -case(usually)

T(n) = max time on any input of size n

Average-case(sometimes)

T(n)=expected time overall input of size n

(Need assumption of stat distribution——equal )

Best-case(bogus)

Worst -case

—relative speed

—absolute speed

Big Idea  Asymptotic analysis

1.Ignore machine dependent

2.Look at growth of T(n) as n->oo

Asymptotic notation

Big O (theta notation) Drop low order terms Ignore leading constants

EX:3n^3 + 90 n^2-5n + 6046=Theta(n^3)

Insertion sort analysis

Worst -case: input reverse sorted

T(n)=qiuhe (j <—2–n)O(j) = O(n^2)

Is Insertion fast?  Not for large n

Merge sort

Merge sort A[1..n]    T(n)

1.if n = 1 ,done    //Theta(1)

2.Recursive sort  //2T(n/2)

A[1..n/2] and A[n/2+1…n]

3.Merge 2 sorted list  //Theta(n)

Key subroutine  Merge

Time = Theta(n) Linear time

Recurrence

T(n) ={ theta(1) if n=1;  2T(n/2)+O(n) if n >1}

Recursion Tree T(n) = 2T(n/2)+c*n (c>0)

T(n) = cn  =                  cn =……  =        cn    cn

/    \                  /      \                      ….    cn

T(n/2) T(n/2)    cn/2    cn/2            O(1)    O(n)

/    \        /    \

T(n/4) T(n/4) T(n/4) T(n/4)

Height of the tree is lg(n)  leaves = n

Total = cn * lg(n) + O(n)= O(n*lg(n))

bounds is 30

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,789评论 0 33
  • 不支持上传文件,所以就复制过来了。作者信息什么的都没删。对前端基本属于一窍不通,所以没有任何修改,反正用着没问题就...
    全栈在路上阅读 2,006评论 0 2
  • “不”有很多不同意思,有人为了证明自己而向别人说不,比如有个人把一件事情委托给另一个人,而有些人会在旁边嘲讽他:“...
    百合花杨贻宸阅读 220评论 0 1
  • 又是一年高考季。分数下来后,就是填志愿了。我也是一枚高三结束的学生,填志愿前,很多人问我,同等学校的话,志愿到底是...
    栗小鲜阅读 561评论 6 2
  • https://www.zhihu.com/question/29878968/answer/141238985 ...
    靖兰亭阅读 544评论 0 51