Design and Analysis of Algorithms_Decrease-and-Conquer
I collect and make up this pseudocode from the book:
<<Introduction to the Design and Analysis of Algorithms_Second Edition>> _ Anany Levitin
Note that throughout the paper, we assume that inputs to algorithms fall within their specified ranges and hence require no verfication. When implementing algorithms as programs to be used in actual applications, you should provide such verfications.
About pseudocode: For the sake of simplicity, we omit declarations of variables and use indentation to show the scope of such statements as for, if and while. As you saw later, we use an arrow <- for the assignment operation and two slashes // for comments.
Algorithm InsertionSort(A[..n-])
// Sorts a given array by insertion sort
// Input: An array A[0..n-1] of n orderable elements
// Output: Array A[0..n-1] sorted in nondecreasing order
for i <- to n- do
v <- A[i]
j <- i-
while j ≥ and A[j] > v do
A[j+] <- A[j]
j <- j-
A[j+] <- v Consider the following version of insertion sort
Algorithm InsertionSort2(A[..n-])
for i <- to n- do
j <- j-
while j ≥ and A[j] > A[j+] do
swap(A[j], A[j+])
j <- j-
What is its time efficiency? How is it compared to that of the version given in the above?
The efficiency classes of both versions will be the same. The Inner loop of InsertionSort consists of one key assignment and one index decrement; the inner loop of InsertionSort2 consists of one key swap(i.e., three key assignments) and one index decrement. If we disregard the time spend on the index decrements, the ratio of the running times should be estimated as 3Ca/Ca = 3; if we take into account the time spent on the index decrements, the ratio's estimate becones (3Ca+Cd)/(Ca+Cd), where Ca and Cd are the times of one key assignment and one index decrement, respectively.
Algorithm DFS(G)
// Implements a depth-first search traversal of a given graph
// Input: Graph G = <V, E>
// Output: Graph G with its vertices marked with consecutive integers
// in the order they've been first encountered by the DFS traversal
make each vertex in V with 0 as a mark of being "unvisited"
count <-
for each vertex v in V do
if v is marked with
dfs(v) dfs(v)
// visits recursively all the unvisited vertices connected to vertex v by a path
// and numbers them in order they are encountered via global variable count
count <- count+; mark v with count
for each vertex w in V adjacent to v do
if w is marked with
dfs(w)
Algorithm BFS(G)
// Implements a breadth-first search traversal of a given graph
// Input: Graph G = <V, E>
// Output: Graph G with its vertices marked with consecutive integers
// in the order they have been visited by the BFS traversal
mark each vetex in V with 0 as a mark of being "unvisited"
count <-
for each vertex v in V do
if v is marked with
bfs(v) bfs(v)
// visits all the unvisited vertices connected to vertex v by a path and assigns them
// the numbers in the order they are visited via global variable count
count <- count+; mark v with count and initialize a queue with v by a path
while the queue is not empty do
for each vertex w in V adjacent to the front vertex do
if w is marked with
count <- count+; mark w with count
add w to the queue
remove the front vertex from the queue
Algorithm JohnsonTrotter(n)
// Implements Johnson-Trotter algorithm for generating permutations
// Input: A positive integer n
// Output: A list of all permutations of {1, ..., n}
initialize the first permutation with ←1 ←2... ←n
while the last permutation has a mobile element do
find its largest mobile element k
swap k and the adjacent integer k's arrow points to
reverse the direction of all the elements that are larger than k
add the new permutation to the list Here is an application of this algorithm for n = 3, with the largest mobile integer shown in underline:
←1←2←3 ←1←3←2 ←3←1←2 →3←2←1 ←2→3←1 ←2←1→3
Consider the following implementation of the algorithm for generating permutations discovered by B.Heap.
Algorithm HeapPermute(n)
// Implements Heap's algorithm for generating permutations
// Input: A positive integer n and a global array A[1..n]
// Output: All permutations of elements of A
if n =
write A
else
for i <- to n do
HeapPermute(n-)
if n is odd
swap A[] and A[n]
else
swap A[i] and A[n] Trace the algorithm by hand for n = 2, 3, and 4.
For n = 2:
12 21
For n = 3 (read along the rows):
123 213
312 132
231 321
For n = 4 (read along the rows):
1234 2134 3124 1324 2314 3214
4231 2431 3421 4321 2341 3241
4132 1432 3412 4312 1342 3142
4123 1423 2413 4213 1243 2143
Write a pseudocode for a recursive algorithm for generating all ^n bit strings of length n.
Algorithm BitstringsRec(n)
// Generates recursively all the bit strings of a given lengt
// Input: A positive integer n
// Output: All bit strings of length n as contents of global array B[0..n-1]
if n =
print(B)
else
B[n-] <- ; BitstringsRec(n-)
B[n-] <- ; BitstirngsRec(n-) Write a nonrecursive algorithm for generating all ^n bit strigns of length n that implements bit strigns as arrays and does not use binary additions.
Algorithm BitstringsNonrec(n)
// Generates nonrecursively all the bit strings of a given length
// Input: A positive integer n
// Output: All bit strings of length n as contents of global array B[0..n-1]
for i <- to n- do
B[i] =
repeat
print(B)
k <- n-
while k ≥ and B[k] =
k <- k-
if k ≥
B[k] <-
for i <- k+ to n- do
B[i] <-
until k = - Design a decrease-and-conquer algorithm for generating all combinations for k items chosen form n, i.e., all k-element subsets of a given n-element set.
There are several decrease-and-conquer algorithms for this problem. They are more subtle than one might expect. Generating combinations in a predefined order(increasing, decreasing, lexicographic) helps with both a design and a correctness proof. The following simple property is very helpful. Assuming with no loss of generality that the underlying set is {1, 2, ..., n}, there are (n-1k-1) k-subsets whose smallest elements is i, i = 1, 2, ..., n-k+1.
Here is a recursive algorithm from "Problems on Algorithms" by Ian Par-berry. call Choose(1, k) where
Algorithm Choose(i, k)
// Generates all k-subsets of {i, i+1, ..., n} stored in global array A[1..k]
// in descending order of their components
if k =
print(A)
else
for j <- i to n-k+ do
A[k] <- j
Choose(j+, k-)
Write a pseudocode for the divide-into-three algorithm for the fake-coin problem.(Make sure that your algorithm handles properly all values of n, not only those that are multiples of 3; We assume that the fake coin is lighter)
If n is multiply of 3(i.e., n mod 3 = 0), we can divide the coins into three piles of n/3 coins each and weigh two of the piles. If n = 3k+1(i.e., n mod 3 = 1), we can divide the coins into the piles of sizes k, k and k+1, or k+1, k+1 and k-1.(We will use the second option.) Finally, if n = 3k+2(i.e., n mod 3 = 2), we will divide the coins into the piles of sizes k+1, k+1 and k. The following pseudocode assumes that there is exactly one fake coin among the coins given and that the fake coin is lighter than the other coins.
if n = the coin is fake
else divide the coins into three piles of ...coins ; mark
weigh the first two piles
if they weight the same and continue with the coins of the third pile
else continue with the lighter of the first two piles There has a very natural question. For large values of n, about how many times faster is this algorithm than the one based on dividing coins into two piles?
The ratio of the number of weighings in the worst case can be approximated for large values of n by
log2n/log3n = log2n/(log32log2n) = log23 ≈ 1.6. Write a pseudocode for the multiplication à la russe algorithm.
Algorithm Russe(n, m)
// Implements multiplication à la russe nonrecursively
// Input: Two positive integer n and m
// Output: The product of n and m
p <-
while n ≠ do
if n mod = p <- p+m
n <- ⌊n/2⌋n/
m <- *m
return p+m Algorithm RusseRec(n, m)
// Implements multiplication à la russe recursively
// Input: Two positive integer n and m
// Output: The product of n and m
if n mod = return RusseRec(n/, 2m)
else if n = return m
else return RusseRec((n-)/, 2m) + m
Write a pseudocode for a nonrecursive implementation of the partition-based algorithm for the selection problem.
Algorithm Selection(A[..n-], k)
// Solves the selection problem by partition-based algortihm
// Input: An array A[0..n-1] of orderable elements and integer k(1 ≤ k ≤ n)
// Output: The value of the k-th smallest element in A[0..n-1]
l <- ; r <- n-
A[n] <- ∞ // append sentinel
while l ≤ r do
p <- A[l] // the pivot
i <- l; j <- r+
repeat
repeat i <- i+ until A[i] ≥ p
repeat j <- j- until A[j] ≤ p do
swap(A[i], A[j])
until i ≥ j
swap(A[i], A[j]) undo last swap
swap(A[l], A[j]) partition
if j > k- r <- j-
else if j < k- l <- j+
else return A[k-] Write a pseudocode for a recursive implementation of the algorithm.
call SelectionRec(A[0..n-1], k) where
Algorithm SelectionRec(A[l..r], k)
// Solves the selection problem by recursive partition-based algorithm
// Input: A subarray A[l..r] of orderable elements and integer k(1 ≤ k ≤ r-l+1)
// Output: The value of the k-th smallest element in A[l..r]
s <- Partition(A[l..r])
if s > l+k- SelectionRec(A[l..s-], k)
else if s < l+k- SelectionRec(A[s+..r], k--s)
else return A[s] The following algorithm for to compute the partition position:
Algorithm Partition(A[l..r])
// Partitions a subarray by using its first element as a pivot
// Input: A subarray A[l..r] of A[0..n-1], defined by its left and right indices l and r(l < r)
// Output: A partition of A[l..r], with the split position returned as this function's value
p <- A[l]
i <- l; j <- r+
repeat
repeat i <- i+ until A[i] ≥ p
repeat j <- j- until A[j] ≤ p
swap(A[i], A[j])
until i ≥ j
swap(A[i], A[j]) // undo last swap when i ≥ j
swap(A[l], A[j])
return j
new words:
disregard: 忽视 estimate: 估计 adjacent: 邻接的
permutation: 排列 lexicographic: 字典序 fake: 假货
multiple: 倍数 product: 产品;[数]乘积 (END_XPJIANG.)
Design and Analysis of Algorithms_Decrease-and-Conquer的更多相关文章
- Design and Analysis of Algorithms_Divide-and-Conquer
I collect and make up this pseudocode from the book: <<Introduction to the Design and Analysis ...
- Design and Analysis of Algorithms_Brute Froce
I collect and make up this pseudocode from the book: <<Introduction to the Design and Analysis ...
- Design and Analysis of Algorithms_Fundamentals of the Analysis of Algorithm Efficiency
I collect and make up this pseudocode from the book: <<Introduction to the Design and Analysis ...
- Design and Analysis of Algorithms_Introduction
I collect and make up this pseudocode from the book: <<Introduction to the Design and Analysis ...
- 6.046 Design and Analysis of Algorithms
课程信息 6.046 Design and Analysis of Algorithms
- 斯坦福大学公开课机器学习: machine learning system design | error analysis(误差分析:检验算法是否有高偏差和高方差)
误差分析可以更系统地做出决定.如果你准备研究机器学习的东西或者构造机器学习应用程序,最好的实践方法不是建立一个非常复杂的系统.拥有多么复杂的变量,而是构建一个简单的算法.这样你可以很快地实现它.研究机 ...
- Algorithms: Design and Analysis, Part 1 - Programming Assignment #1
自我总结: 1.编程的思维不够,虽然分析有哪些需要的函数,但是不能比较好的汇总整合 2.写代码能力,容易挫败感,经常有bug,很烦心,耐心不够好 题目: In this programming ass ...
- Algorithms: Design and Analysis, Part 1 - Problem Set 1 - Question 5
最后一个图像,用画图软件绘制了一下,自己的直接主观判断还是有些小问题的 注意:最后的灰色的线条会超过橙色的线条
- EE就业最好的方向是转CS,其次是VLSI/ASIC DESIGN & VERIFICATION
Warald在2012年写过一篇文章<EE现在最好就业的方向是VLSI/ASIC DESIGN VERIFICATION>,三年过去了,很多学电子工程的同学想知道现在形势如何. 首先,按照 ...
随机推荐
- Alpha 测试
活动助手Alpha--测试篇 测试分工 人员 分工 测试 牛姐 Android开发/ui设计 功能测试 橙汁 Android开发 功能测试 洪 数据库开发 数据库结构测试 佳凯 数据库设计与开发 接口 ...
- Ajax技术原理小结
ajax:Asynchronous Javascript and XML 异步Javascript 和XML. 是一种创建交互式网页应用的网页开发技术. 1.0 优势: ...
- hihoCoder1388 Periodic Signal(2016北京网赛F:NTT)
题目 Source http://hihocoder.com/problemset/problem/1388 Description Profess X is an expert in signal ...
- 在DrawingVisual上绘制圆形的进度条,类似于IOS系统风格。
1.说明:在WPF中,文件下载时需要显示下载进度,由于系统自带的条型进度条比较占用空间,改用圆形的进度条,需要在DrawingVisual上呈现. 运行的效果如图: private Point Get ...
- Sizeof面试题
sizeof()功能:计算数据空间的字节数1.与strlen()比较 strlen()计算字符数组的字符数,以"\0"为结束判断,不计算为'\0'的数组元素. ...
- [机器学习] 虚拟机VMware中使用Ubuntu的联网问题
在VMware中安装Ubuntu要解决两个问题: 1.VMware Tools安装使用 2.Ubuntu联网的虚拟机设置 1.VMware Tools安装 它的作用就是使用户可以从物理主机直接往虚拟机 ...
- 【转】logback logback.xml常用配置详解(一)<configuration> and <logger>
原创文章,转载请指明出处:http://aub.iteye.com/blog/1101260, 尊重他人即尊重自己 详细整理了logback常用配置, 不是官网手册的翻译版,而是使用总结,旨在更快更透 ...
- 纯Java配置使用slf4j配置log4j
工程目录如下 代码里面用的是slf4j,但是想要用log4j来管理日志,就得添加slf4j本来的jar,然后添加log4j和slf4j箱关联的jar即可. 如果是maven项目的话添加下面的依赖即可 ...
- JQUERY attr prop 的区别 一个已经被淘汰
在做jquery 全选 全不选的项目中, 1..prop( propertyName ) 获取匹配集合中第一个元素的Property的值 2. .prop( propertyName, value ) ...
- 百度网盘生成二维码api
分享出自精神,灵感来自大脑,在百度云网盘分享每一个文件,都会在页面生成一个二维码扫描的图片: 我就进一步看了该图片的地址: 发现没有,圈圈内是不是有点眼熟,就跟其他二维码api接口一样,只要盗用这段东 ...