Design and Analysis of Algorithms_Divide-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 MergeSort(A[..n-])
// Sorts array A[0..n-1] by recursive mergesort
// Input: An array A[0..n-1] of orderable element
// Output: Array A[0..n-1] sorted in nondecreasing order
if n >
copy A[..⌊n/⌋-] to B[..⌊n/⌋-]
copy A[⌊n/⌋..n-] to C[..⌈n/⌉-]
MergeSort(B[..⌊n/⌋-])
MergeSort(C[..⌈n/⌉-])
Merge(B, C, A)
Algorithm Merge(B[..p-], C[..q-], A[..p+q-])
// Merge two sorted arrays into one sorted array
// Input: Arrays B[0..p-1] and C[0..q-1] both sorted
// Output: Sorted array A[0..p+q-1] of the elements of B and C
i <- ; j <- ; k<-
while i < p and j < q do
if B[i] ≤ C[j]
A[k] <- B[i]; i <- i+
else
A[k] <- C[j]; j <- j+
k <- k+
if i = p
copy C[j..q-] to A[k..p+q-]
else
copy B[i..p-] to A[k..p+q-]
Write a pseudocode for a divide-and-conquer algorithm for finding a position of the largest element in an array of n numbers.
Call Algorithm MaxIndex(A[0..n-1]) where
Algorithm MaxIndex(A[l..r])
// Input: A portion of array A[0..n-1] between indices l and r(l ≤ r)
// Output: The index of the largest element in A[l..r]
if l = r return A[l]
else
temp1 <- MaxIndex(A[l..⌊(l+r)/2⌋])
temp2 <- MaxIndex(A[⌊(l+r)/2⌋+1..r])
if temp1 ≥ temp2
return temp1
else
return temp2 The recurrence for the number of element comparisons is C(n) = n - 1. A simple standard scan through the array in question requires the same number of key comparisons but avoid the overhead associated with recurise calls.
Write a pseudocode for a divide-and-conquer algorithm for finding values of both the largest and smallest elements in an array of n numbers.
Call Algorithm MinMax(A[0..n-1], minval, maxval) where
Algorithm MinMax(A[l..r], minval, maxval)
// Finds the values of the smallest and largest elements in a given subarray
// Input: A portion of array A[0..n-1] between indices l and r(l ≤ r)
// Output: The value of the smallest and largest elements in A[l..r]
// assigned to minval and maxval, respectively
if l = r
minval <- A[l]; maxval <- A[l]
else if r-l =
if A[l] ≤ A[r]
minval <- A[l]; maxval <- A[r]
else
minval <- A[r]; maxval <- A[l]
else // r-l > 1
MinMax(A[..⌊(l+r)/2⌋)], minval, maxval)
MinMax(A[⌊(l+r)/2⌋+1..r], minval2, maxval2)
if minval2 < minval
minval <- minval2
if maxval2 > maxval
maxval <- maxval2
The number of element comparison C(n) = (3/2)n - 2.
This algorithm make about 25% fewer comparisons——1.5n compared to 2n——than the brute-force algorithm.(Note that if we didn't stop recursive calls when n = 2, we would've lost this gain.) In fact, the algorithm is optimal in terms ofthe number of comparisons made. As a practical matter, however, it might not be faster than the brute-force algorithm because of the recursion-related overhead.
Algorithm QuickSort(A[l..r])
// Sorts a subarray by quicksort
// Input: A subarray A[l..r] of A[0..n-1], defined by its left and right indices l and r
// Output:Subarray A[l..r] sorted in nondecreasing order
if l < r
s <- Partition(A[l..r]) // s is a split position
QuickSort(A[l..s-])
QuickSort(A[s+..r]) 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
Design an algorithm to rearrange elements of a given array of n real numbers so that all its negative elements precede all its positive elements. Your algorithm should be both time and space efficient.
The following algorithm uses the partition idea similar to that of quicksort, although it's implemented somewhat differently. Namely, on each iteration the algorithm maintains three section(possible empty) in a given array: all the elements in A[0..i-1] are negative, all the elements in A[i..j] are unknown, and all the elements in A[j+1..n-1] are nonnegative, on each iteration, the algorithm shrinks the size of the unknown section by one element either from the left or from the right.
Algorithm NegBeforePos(A[..n-])
// Puts negative elements before position(and zeros, if any) in an array
// Input: Array A[0..n-1] of real numbers
// Output: Array A[0..n-1] in which all its negative elements precede nonnegative
i <- ; j <- n-
while i ≤ j do // i < j would suffice
if A[i] < // shrink the unknown section from the left
i <- i+
else // shrink the unknown section from the right
swap(A[i], A[j])
j <- j- Of cource, we can also use the under mathod, but this method lead a problem is that if all of the elements is nonnegative or nonpositive, we must use a sentinel.
Algorithm NegBeforePos(A[..n-])
A[-] <- -; A[n] <- // sentinel
i <- ; j <- n-
while i < j do
while A[i] ≤ do
i <- i+
while A[j] ≥ do
j <- j-
swap A[i] and A[j]
swap A[i] and A[j] // undo the last swap Note: If we want all the zero elements placed after all the negative elements but before all the positive ones, the problem becomesthe Dutch flag problem, like the next Algorithm.
The Dutch flag problem is to rearrange any array of characters R, W, and B(red, white, and blue are the color of the Dutch national flag) so that all the R's come first, the W's come next, and the B's come last. Design a linear in-place algorithm for this problem.
The follwing algorithm uses the partition idea similar to that of quick-sort. On each iteration, the algorithm maintains four sections(possibly empty) in a given array: all the elements in A[0..r-1] are filled with R's, all the elements in A[r..w-1] are filled with W's, all the elements in A[w..b] are unknown, and all the elements in A[b+1..n-1] are filled with B's. On each iteration, the algorithm shrinks the size of unknown section by one element either from the left or from the right. Algorithm DutchFlag(A[..n-])
// Sorts an array with values in a three-element set
// Input: An array A[0..n-1] of characters from {'R', 'W', 'B'}
// Output: Array A[0..n-1] in which all its R elements precede all its W
// elements that precede all its B elements
r <- ; W <- ; b <- n-
while w ≤ b do
if A[w] = 'R'
swap(A[r], A[w]); r <- r+; w <- w+
else if A[w] = 'W'
w <- w+
else // A[w] = 'B'
swap(A[w], A[b]); b <- b-
Algorithm BinarySearch(A[..n-], K)
// Implements nonrecursive binary search
// Input: An array A[0..n-1] sorted in ascending order and a search key K
// Output: An index of the array's element that is equal to K or -1 if there is no such element
l <- ; r <- n-
while l ≤ r do
m <- ⌊(l+r)/2⌋
if K = A[m] return m
else if K < A[m] r <- m-
else l <- m+
return -
Write a pseudocode for a recursive version of binary search.
Call BSR(A[..n-], K) where
Algorithm BSR(A[..n-], K)
// Implements binary search recursively
// Input: A sorted (sub)array A[l..r] and a search key K
// Output: An index of the array's element equal to K or -1 if there is no such elements
if l > r return -
else m <- ⌊(l+r)/2⌋
if K = A[m] return m
else if K < A[m] return BSR(A[l..m-], K)
else return BSR(A[m+..r], K)
Algorithm Height(T)
// Computes recursively the height of a binary tree
// Input: A binary tree T
// Output: The height of T
if T = Ø return -
else return max{Height(TL), Height(TR)} + 1
The following algorithm for compute the number of leaves in a binary tree.
Algorithm LeafCounter(T)
// Computes recursively the number of leaves in a binary tree
// Input: A binary tree T
// Output: The number of leaves in T
if T = Ø return // empty tree
else if TL = Ø and TR = Ø return // one-node tree
else return LeafCounter(TL) + LeafCounter(TR) // general case
Write a pseudocode for one of the classic traversal algorithm(preorder, inorder, and postorder) for binary trees. Assuming that your algorithm is recursive, find the number of recursive calls made.
Here is a pseudocode of the preorder traversal: Algorithm Preorder(T)
// Implements the preorder traversal of a binary tree
// Input: Binary tree T(with labeled vertices)
// Output: Node labels listed in preorder
if T ≠ Ø
print label of T's root
PreOrder(TL) // TL is the root's left subtree
PreOrder(TR) // TR is the root's right subtree The number of calls, C(n), made by the algorithm is equal to the number of nodes, both internal and external, in the extended tree. Hence, C(n) = 2n + 1
new words:
portion: 部分 divide and conquer: 分而治之;各个击破
optimal: 最佳的 split: 分裂 pivot: 枢轴 precede: 在...之前; 优于
partition: 分区 namely: 换句话说, 也就是 shrink: 缩小
suffice: 足够 Dutch: 荷兰 undo: 撤销
(Terminator: XPJIANG)
Design and Analysis of Algorithms_Divide-and-Conquer的更多相关文章
- Design and Analysis of Algorithms_Decrease-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>,三年过去了,很多学电子工程的同学想知道现在形势如何. 首先,按照 ...
随机推荐
- linux yum安装jdk
>>>>>>>>>> 实例: yum安装jdk 1.查看当前的jdk版本,并卸载 (注1:rpm -qa ###解释:查询所有安装的rpm包 ...
- 数据类型和Json格式
1. 前几天,我才知道有一种简化的数据交换格式,叫做yaml. 我翻了一遍它的文档,看懂的地方不多,但是有一句话令我茅塞顿开. 它说,从结构上看,所有的数据(data)最终都可以分解成三种类型: 第一 ...
- 2015ACM/ICPC亚洲区长春站
5532 Almost Sorted Array 题目大意:给你一个序列,如果它拿掉其中一个数后,可以是该序列成为非递减或非递增序列,则输出YES. 有两种思路,第一种代码比较简单,是LIS,复杂度n ...
- sprintf溢出的bug
向printf.sprintf这种函数在编译时很难检查错误,所以程序员必须小心.比如我就遇到了这样的bug: void test() { ]; sprintf(t,"); } //执行spr ...
- vs发布的程序不依赖运行时库msvcp100.dll
[摘要:msvcr100.dll:MS Visual C Runtime 100 msvcp100.dll:MS Visual CPp 100 vs建立的工程,运转时库的范例有MD(MDd)战MT ...
- 点 击 直 接加我QQ的功能
<a target="_blank" href="tencent://message/?uin=2814920598&Site=&Menu=yes& ...
- 随堂笔记javascript篇之chrome调试:
在征求到许老师的同意之后,我用javascript脚本语言来完成我的课堂作业,初学一门语言,刚开始也许是初生牛犊不怕虎,接受一门新的语言而且用来完成作业.一开始老师是拒绝的,他说我这样是太麻烦了.对于 ...
- svn: E155004 is already locked 解决方案
在出错文件夹下(或整个工程项目),鼠标右键TortoiseSVN->Clean up. SVN错误:Attempted to lock an already-locked dir 1.出现这个问 ...
- 通过Gulp使用Browsersync实现浏览器实时响应文件更改
Gulp是什么鬼 Browsersync又是什么鬼 如何安装使用Browsersync 安装 使用 效果图 参考 Gulp是什么鬼 Gulp是一种基于node.js的构建工具,有关构建工具的概念请移步 ...
- <meta>指定浏览器模式(browser mode)或文档模式(document mode)无效
这是前两天解决的一个故障,准确的说它不是一个SharePoint的问题,而是IE8浏览器或者说是HTML代码的问题,但我感觉还是挺有意思的,所以贴上来分享一下. 基础知识 简单的讲,就是IE浏览器中有 ...