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的更多相关文章

  1. Design and Analysis of Algorithms_Decrease-and-Conquer

    I collect and make up this pseudocode from the book: <<Introduction to the Design and Analysis ...

  2. Design and Analysis of Algorithms_Brute Froce

    I collect and make up this pseudocode from the book: <<Introduction to the Design and Analysis ...

  3. 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 ...

  4. Design and Analysis of Algorithms_Introduction

    I collect and make up this pseudocode from the book: <<Introduction to the Design and Analysis ...

  5. 6.046 Design and Analysis of Algorithms

    课程信息 6.046 Design and Analysis of Algorithms

  6. 斯坦福大学公开课机器学习: machine learning system design | error analysis(误差分析:检验算法是否有高偏差和高方差)

    误差分析可以更系统地做出决定.如果你准备研究机器学习的东西或者构造机器学习应用程序,最好的实践方法不是建立一个非常复杂的系统.拥有多么复杂的变量,而是构建一个简单的算法.这样你可以很快地实现它.研究机 ...

  7. Algorithms: Design and Analysis, Part 1 - Programming Assignment #1

    自我总结: 1.编程的思维不够,虽然分析有哪些需要的函数,但是不能比较好的汇总整合 2.写代码能力,容易挫败感,经常有bug,很烦心,耐心不够好 题目: In this programming ass ...

  8. Algorithms: Design and Analysis, Part 1 - Problem Set 1 - Question 5

    最后一个图像,用画图软件绘制了一下,自己的直接主观判断还是有些小问题的 注意:最后的灰色的线条会超过橙色的线条

  9. EE就业最好的方向是转CS,其次是VLSI/ASIC DESIGN & VERIFICATION

    Warald在2012年写过一篇文章<EE现在最好就业的方向是VLSI/ASIC DESIGN VERIFICATION>,三年过去了,很多学电子工程的同学想知道现在形势如何. 首先,按照 ...

随机推荐

  1. Appium中部分api的使用方法

    使用的语言是java,appium的版本是1.3.4,java-client的版本是java-client-2.1.0,建议多参考java-client-2.1.0-javadoc. 1.使用Andr ...

  2. [poj2337]求字典序最小欧拉回路

    注意:找出一条欧拉回路,与判定这个图能不能一笔联通...是不同的概念 c++奇怪的编译规则...生不如死啊... string怎么用啊...cincout来救? 可以直接.length()我也是长见识 ...

  3. dbflow 批量 增删查改

    @ModelContainer @Table(database = DemoDatabase.class) class Person extends BaseModel implements Seri ...

  4. mysql数据去除重复及相关优化(转)

    由于mysql不支持同时对一张表进行操作,即子查询和要进行的操作不能是同一张表,因此需要通过临时表中专以下. 1.单字段重复 生成临时表,其中uid是需要去重的字段 create table tmp_ ...

  5. Git的简单使用教程

    Git是一款免费.开源的分布式版本控制系统,用于敏捷高效地处理任何或小或大的项目. GitHub则可以托管各种git库,并提供一个web界面,但与其它像 SourceForge或Google Code ...

  6. OSG中找到特定节点的方法

    OSG中找到特定节点的方法 转自:http://38288890.blog.163.com/blog/static/19612845320072721549504/ 为了在OSG中找到需要的节点并对节 ...

  7. debian C++ OTL库 用 unixodbc 连接 mysql 小记

    这个东东也是折腾了几天,网上很多文章可能已经过时,所以写下不同,以备后用. 参考网址: http://blog.csdn.net/genganpeng/article/details/7402229 ...

  8. 工作中的sql语句总结

    1,查找mysql 数据库 自动 添加 序号 字段列1,2,3,4 ) AS rowno,ip,startcount ) b 2,mysql的分页语句 limit后面第一个参数是index,从0开始: ...

  9. django错误-NoReverseMatch at /admin/

    错误提示: NoReverseMatch at /admin/ Reverse for 'logout' with arguments '()' and keyword arguments '{}' ...

  10. Java中线程的生命周期

    首先简单的介绍一下线程: 进程:正在运行中的程序.其实进程就是一个应用程序运行时的内存分配空间. 线程:其实就是进程中的一条执行路径.进程负责的是应用程序的空间的标示.线程负责的是应用程序的执行顺序. ...