Analysis of Algorithms Week 1
最近开始学习Coursera上普林斯顿的算法分析课程,后续会记录下学习过程,这次是第一周的内容。
课程主页:https://www.coursera.org/learn/analysis-of-algorithms
Exercise
1.14
Follow through the steps given for quicksort to solve the recurrence:
解:两边乘以
相减可得
两边同除
所以
1.15
Show that the average number of exchanges used during the first partitioning stage (before the pointers cross) is
首先回顾源代码:
public class Quick
{
private static int partition(Comparable[] a, int lo, int hi)
{
int i = lo, j = hi+1;
while (true)
{
while (less(a[++i], a[lo])) if (i == hi) break;
while (less(a[lo], a[--j])) if (j == lo) break;
if (i >= j) break;
exch(a, i, j);
}
exch(a, lo, j);
return j;
}
private static void sort(Comparable[] a, int lo, int hi)
{
if (hi <= lo) return;
int j = partition(a, lo, hi);
sort(a, lo, j-1);
sort(a, j+1, hi);
}
}
题目的意思是计算exch(a, lo, j)之前的平均交换次数。
不妨设元素为
那么在主元为
因为
1.17
If we change the first line in the quicksort implementation given in the lecture to call insertion sort when the subfile size is not greater than
Solve this recurrence.
对于
递推可得
所以对于
1.18
所以
不考虑常数项,作图可得
当M= 8 时取最小值
代码如下:
import numpy as np
import matplotlib.pyplot as plt
M = np.arange(1, 100)
d1 = M * (M - 1) / (4 * (M + 1))
d2 = 2 * np.cumsum(1 / M)
f = d1 - d2
plt.plot(M, f)
plt.show()
print("当M=", M[np.argmin(f)], "时取最小值")
Problem
1
相减可得
累加可得
2
Which of the following is a drawback to analyzing algorithms by proving O- upper bounds on the worst case?
- Generally cannot be used to predict performance.
- Likely to be too much detail in the analysis.
- Generally cannot be used to compare algorithms.
- Input model may be unrealistic.
显然答案如下:
Generally cannot be used to predict performance.
Generally cannot be used to compare algorithms.
v1.5.2