网易公开课《算法导论》的学习笔记,第一节课
先贴上一段Charles Leiserson教授的话。
进入正题,先讲了一下插入排序(Insertion Sorts)。
Problem:sorting
Input: sequence < a1, a2 ,…, an > of numbers
Output: permutation <a’1, a’2 ,…, a’n>, such that a’1 <= a’2 <= a’3 … <= a’n
Insertion Sort.
1 | //Pseudocode |
算法分析,见下图。
数组A,1~j-1是已经排好序的,现将j插入到已经排好序的数组中。令j的值为key,分别与j-1,j-2,j-3,…比较,直到找到合适的位置,插入。
后面的Example演示了这一过程。
Running time:
1 | Depends on input(eg. already sorted) |
Kinds of analysis
1 | Worst-case(usually) |
What is insertion sort’s worst-case time?
1 | Depends on computer |
Asympototic notation
1 | theta-notation: |
ps:theta equals to $$\theta$$
一张图来对比。
Insertion sort analysis
Worst-case:input reverse sorted
$$T\left( n\right) =\sum _{j=2}^{n}\Theta \left( j\right) = \Theta\left( n^{2}\right)$$
(Arithmetic series)
Is insertion sort fast?
1 | -moderately for small n |
Merge sort
1 | Merge sort A[1,...n] --------T(n) |
Key subroutine: Merge
两个已经排好序的数组。分别有两个指针指向首元素,比较大小,小的就提取出来,然后指针指向后一位。时间与两个数组之和成正比。
Recursive
T(n) = theta(1), if n = 1 (use omit)
2T(n/2) + theta(n), if n > 1
Recursive tree. T(n) = 2T(n/2) + cn, const c > 0
Performance
树的长度lg(n),叶子个数n。
最后得出mergesort的时间 theta(nlgn)。