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. 配置Tomcat使用https协议

    一.  创建tomcat证书 这里使用JDK自带的keytool工具来生成证书: 1. 在jdk的安装目录\bin\keytool.exe下打开keytool.exe 2. 在命令行中输入以下命令: ...

  2. Codeforces Round #367 (Div. 2)

    A题 Beru-taxi 随便搞搞.. #include <cstdio> #include <cmath> using namespace std; int a,b,n; s ...

  3. php+mysql+smarty+oop

    php+mysql+smarty+oop 设计新闻系统简单的UML模 powerdesigner和diagram designer 设计所需环境.模块.模板样式 数据库uml设计和创建数据库结构 db ...

  4. 求两条线段交点zz

    "求线段交点"是一种非常基础的几何计算, 在很多游戏中都会被使用到. 下面我就现学现卖的把最近才学会的一些"求线段交点"的算法说一说, 希望对大家有所帮助. 本 ...

  5. 洛谷 P1736 创意吃鱼法 Label:dp || 前缀和

    题目描述 回到家中的猫猫把三桶鱼全部转移到了她那长方形大池子中,然后开始思考:到底要以何种方法吃鱼呢(猫猫就是这么可爱,吃鱼也要想好吃法 ^_*).她发现,把大池子视为01矩阵(0表示对应位置无鱼,1 ...

  6. TCP/IP连接状态

    1.建立连接协议(三次握手)(1)客户端发送一个带SYN标志的TCP报文到服务器.这是三次握手过程中的报文1.(2) 服务器端回应客户端的,这是三次握手中的第2个报文,这个报文同时带ACK标志和SYN ...

  7. input type=file 图片上传相关

    HTML: <input type="file" name="address"   onchange='PreviewImage(this)' value ...

  8. ZeroMQ接口函数之 :zmq_close - 关闭ZMQ socket

    ZeroMQ 官方地址 :http://api.zeromq.org/4-0:zmq_close zmq_close(3) ØMQ Manual - ØMQ/3.2.5 Name zmq_close  ...

  9. MySQL查询语句(select)详解(1)

    1.查询记录 select*from 表名 [where 条件];eg:select*from students;//查询 students 表中所有记录,所有字段的值都显示出来select fiel ...

  10. 关于如何在MVC中 执行JS

    Response.Write("<script>KHTPREFERENCE()</script>"); return this.MessageResult( ...