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>,三年过去了,很多学电子工程的同学想知道现在形势如何. 首先,按照 ...
随机推荐
- tomcat 配置项目指定域名
<Host name="www.xxx.com" appBase="D:/tomcat/webapps/web"> <alias>xxx ...
- Codeforces 307 div2 E.GukiZ and GukiZiana 分块
time limit per test 10 seconds memory limit per test 256 megabytes input standard input output stand ...
- 我的c++学习(9)指针
◆ 1.指针变量的赋值.初始化与简单应用 ,y; y=; // y可以理解成该存储单元的当前名字 int *ip; // ip是一个指针(变量) ip=&y; // ip是存储空间y的地址 c ...
- Validation-jQuery表单验证插件使用方法
http://www.cnblogs.com/shuang121/archive/2012/04/23/2466628.html 作用 jquery.validate是jquery旗下的一个验证框架, ...
- WebForms 开发基础
webform开发方式 xml - 可扩展的标记语言 HTML - 超文本标记语言 运行: 点击启动按钮 - 好处:可以卡断点 弊端:启动特别慢 在html上右键,在浏览器中查看 - 好处:启动特别快 ...
- [计算机故障]windows8+IE11显示无法登陆网页
同事的一款SURFACE,跑的WINDOWS 8.1.最近发现从开始菜单里的win8.1的浏览器可以上网,但是通过任务栏的快捷方式,又上不了网.尝试重置了IE11,安装了Google Chrome.但 ...
- localstorage 的属性改变问题
localstorage 得到的是对象,我们打算改对象的某个属性的值,方法是 通过临时变量对象得到,改变临时变量,然后把临时变量给localstorage的方法 var localS = windo ...
- C++强制类型转换
C语言强制类型转换过于粗暴,任意类型之间都可以进行转换,编译很难判断其正确性; 难于定位,在源码中无法快速定位所有使用强制类型转换的语句. C++将强制类型转换分为4种不同的类型:static_cas ...
- win 10 常见问题
Microsoft Edge Can't Open Local Domains IE Edge浏览器打不开本地站点 解决方法:解决方法
- C中嵌入python
嵌入 与python的扩展相对,嵌入是把Python解释器包装到C的程序中.这样做可以给大型的,单一的,要求严格的,私有的并且(或者)极其重要的应用程序内嵌Python解释器的能力.一旦内嵌了Pyth ...