Skip to content

Commit

Permalink
CLRS C06
Browse files Browse the repository at this point in the history
  • Loading branch information
Louis1992 committed Jun 23, 2015
1 parent 4aae037 commit b8046d1
Show file tree
Hide file tree
Showing 22 changed files with 551 additions and 97 deletions.
56 changes: 56 additions & 0 deletions C06-Heapsort/6.1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
### Exercises 6.1-1
***
What are the minimum and maximum numbers of elements in a heap of height h?

### `Answer`
最多就是一颗很完美的二叉树,是2\*\*(h+1) − 1 ; 最少的话最后一层只有一个,是2\*\*h


### Exercises 6.1-2
***
Show that an n-element heap has height ⌞lg n⌟

### `Answer`
![](http://latex.codecogs.com/gif.latex? 2^{h+1}-1\\geq x \\geq 2^{h} \\rightrightarrows \\lg{x} \\geq h \\geq \\lg\(x+1\)-1 )

所以h = ⌞lg n⌟

### Exercises 6.1-3
***
Show that in any subtree of a max-heap, the root of the subtree contains the largest value occurring anywhere in that subtree.

### `Answer`
这就是最大堆的性质.

### Exercises 6.1-4
***
Where in a max-heap might the smallest element reside, assuming that all elements are distinct?

### `Answer`
肯定是在叶子节点.

### Exercises 6.1-5
***
Is an array that is in sorted order a min-heap?

### `Answer`
没有说明是递增数组还是递减数组,所以不一定.

### Exercises 6.1-6
***
Is the sequence [23, 17, 14, 6, 13, 10, 1, 5, 7, 12] a max-heap?

### `Answer`
不是,7 > 6

### Exercises 6.1-7
***
Show that, with the array representation for storing an n-element heap, the leaves are the nodes indexed by ⌞n/2⌟ + 1, ⌞n/2⌟ + 2, ... , n.

### `Answer`
挺容易推的,因为每增加两个节点,树的叶子节点就会往后推移一位.再注意一下取整的位置就行.


***
Follow [@louis1992](https://github.com/gzc) on github to help finish this task.

70 changes: 70 additions & 0 deletions C06-Heapsort/6.2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
### Exercises 6.2-1
***
Using Figure 6.2 as a model, illustrate the operation of MAX-HEAPIFY(A, 3) on the array A = 27,17, 3, 16, 13, 10, 1, 5, 7, 12, 4, 8, 9, 0.

### `Answer`
![](./repo/s2/1.png)


### Exercises 6.2-2
***
Starting with the procedure MAX-HEAPIFY, write pseudocode for the procedure MIN- HEAPIFY(A, i), which performs the corresponding manipulation on a min-heap. How does the running time of MIN-HEAPIFY compare to that of MAX-HEAPIFY?

### `Answer`

MIN-HEAPIFY(A, i):
l <- LEFT(i)
r <- RIGHT(i)
if l ≤ heap-size[A] and A[l] < A[i]:
then smallest <- l
else smallest <- i
if r ≤ heap-size[A] and A[r] < A[smallest]:
then smallest <- r
if smallest ≠ i:
then swap(A[i], A[smallest])
MIN-HEAPIFY(A, smallest)

### Exercises 6.2-3
***
What is the effect of calling MAX-HEAPIFY(A, i) when the element A[i] is larger than its children?

### `Answer`
函数直接返回.

### Exercises 6.2-4
***
What is the effect of calling MAX-HEAPIFY(A, i) for i > heap-size[A]/2?

### `Answer`
这种情况下,这个节点是叶子节点.

### Exercises 6.2-5
***
The code for MAX-HEAPIFY is quite efficient in terms of constant factors, except possibly for the recursive call in line 10, which might cause some compilers to produce inefficient code. Write an efficient MAX-HEAPIFY that uses an iterative control construct (a loop) instead of recursion.

### `Answer`

MIN-HEAPIFY(A, i):
while i ≤ heap-size[A]:
l <- LEFT(i)
r <- RIGHT(i)
if l ≤ heap-size[A] and A[l] > A[i]:
then largest <- l
else largest <- i
if r ≤ heap-size[A] and A[r] > A[largest]:
then largest <- r
if largest ≠ i:
then swap(A[i], A[largest])
i = largest

### Exercises 6.2-6
***
Show that the worst-case running time of MAX-HEAPIFY on a heap of size n is Ω(lg n). (Hint: For a heap with n nodes, give node values that cause MAX-HEAPIFY to be called recursively at every node on a path from the root down to a leaf.)

### `Answer`
最坏情况是从root一直递归到leaf,因为heap的高度为⌞lg n⌟,所以最坏运行时间是Ω(lgn).


***
Follow [@louis1992](https://github.com/gzc) on github to help finish this task.

Expand Down
34 changes: 34 additions & 0 deletions C06-Heapsort/6.3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
### Exercises 6.3-1
***
Using Figure 6.3 as a model, illustrate the operation of BUILD-MAX-HEAP on the array A = [5, 3, 17, 10, 84, 19, 6, 22, 9].

### `Answer`
![](./repo/s3/1.png)


### Exercises 6.3-2
***
Why do we want the loop index i in line 2 of BUILD-MAX-HEAP to decrease from ⌞length[A]/2⌟ to 1 rather than increase from 1 to ⌞length[A]/2⌟?

### `Answer`
如果先从1开始,它的子树并不是最大堆,肯定不能这样迭代.

### Exercises 6.3-3
***
Show that there are at most ![](http://latex.codecogs.com/gif.latex? \\lceil n/\(2^{h+1}\) \\rceil) nodes of height h in any n-element heap.

### `Answer`
根据[6.1.1](./6.1.md)我们有

![](http://latex.codecogs.com/gif.latex? 2^{h_0} \\le n \\le 2^{h_0+1}-1 )

令k为层数,h0为树的高度,root结点k = 0.

![](http://latex.codecogs.com/gif.latex? \\lceil n/\(2^{h+1}\) \\rceil \\le \\lceil \(2^{h_0+1}-1\)/\(2^{h+1}\) \\rceil = 2^{h_0-h})

每层都满,等式成立;否则,叶子层是小于.


***
Follow [@louis1992](https://github.com/gzc) on github to help finish this task.

Expand Down
45 changes: 45 additions & 0 deletions C06-Heapsort/6.4.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
### Exercises 6.4-1
***
Using Figure 6.4 as a model, illustrate the operation of HEAPSORT on the array A = [5, 13, 2, 25, 7, 17, 20, 8, 4].

### `Answer`
![](./repo/s4/1.png)


### Exercises 6.4-2
***
Argue the correctness of HEAPSORT using the following loop invariant:
• At the start of each iteration of the for loop of lines 2-5, the subarray A[1...i] is a max-heap containing the i smallest elements of A[1...n], and the subarray A[i + 1...n] contains the n - i largest elements of A[1...n], sorted.

### `Answer`
这个循环不变式比较明显,就不详细写啦

### Exercises 6.4-3
***
What is the running time of heapsort on an array A of length n that is already sorted in increasing order? What about decreasing order?

### `Answer`
如果是递减序列,是最差的情况.需要

![](http://latex.codecogs.com/gif.latex? \\sum_{i = 1}^{n}\\lg{i} = \\lg{n!} = \\Theta\(n\\lg{n}\) )

如果是按递增序列,也需要![](http://latex.codecogs.com/gif.latex?\\Theta\(n\\lg{n}\) ),因为Max_heapify的cost并没变.


### Exercises 6.4-4
***
Show that the worst-case running time of heapsort is Ω(n lg n).

### `Answer`
跟6.3.3一样

### Exercises 6.4-5
***
Show that when all elements are distinct, the best-case running time of heapsort is Ω(n lg n).

### `Answer`
It is actually a hard problem, see [solution](http://stackoverflow.com/questions/4589988/lower-bound-on-heapsort)

***
Follow [@louis1992](https://github.com/gzc) on github to help finish this task.

Expand Down
76 changes: 76 additions & 0 deletions C06-Heapsort/6.5.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
### Exercises 6.5-1
***
Illustrate the operation of HEAP-EXTRACT-MAX on the heap A = [15, 13, 9, 5, 12, 8, 7, 4, 0, 6, 2, 1].

### `Answer`
![](./repo/s5/1.png)


### Exercises 6.5-2
***
Illustrate the operation of MAX-HEAP-INSERT(A, 10) on the heap A = [15, 13, 9, 5, 12, 8,7, 4, 0, 6, 2, 1]. Use the heap of Figure 6.5 as a model for the HEAP-INCREASE-KEY call.

### `Answer`
![](./repo/s5/2.png)

### Exercises 6.5-3
***
Write pseudocode for the procedures HEAP-MINIMUM, HEAP-EXTRACT-MIN, HEAP- DECREASE-KEY, and MIN-HEAP-INSERT that implement a min-priority queue with a min-heap.

### `Answer`
这是最大优先级队列的实现,最小也类似.

[p_queue.h](./p_queue.h)

[p_queue.cpp](./p_queue.cpp)


### Exercises 6.5-4
***
Why do we bother setting the key of the inserted node to -∞ in line 2 of MAX-HEAP- INSERT when the next thing we do is increase its key to the desired value?

### `Answer`
为了使HEAP-INCREASE-KEY的条件成立

### Exercises 6.5-5
***
Argue the correctness of HEAP-INCREASE-KEY using the following loop invariant:
• At the start of each iteration of the while loop of lines 4-6, the array A[1...heap- size[A]] satisfies the max-heap property, except that there may be one violation: A[i] may be larger than A[PARENT(i)].

### `Answer`
依然是很明显的循环不变式.

### Exercises 6.5-6
***
Show how to implement a first-in, first-out queue with a priority queue. Show how toimplement a stack with a priority queue. (Queues and stacks are defined in Section 10.1.)

### `Answer`

* 先进先出队列: 每次都给新插入的元素赋予更低的优先级即可.
* 栈:每次都给新插入的元素赋予更高的优先级.


### Exercises 6.5-7
***
The operation HEAP-DELETE(A, i) deletes the item in node i from heap A. Give animplementation of HEAP-DELETE that runs in O(lg n) time for an n-element max-heap.

### `Answer`

HEAP-DELETE(A, i):
A[i] = A[A.heap-size]
A.heap-size -= 1
MAX-HEAPIFY(A, i)

### Exercises 6.5-8
***
Give an O(n lg k)-time algorithm to merge k sorted lists into one sorted list, where n is thetotal number of elements in all the input lists. (Hint: Use a min-heap for k-way merging.)

### `Answer`
The problem occurs in [leetcode](https://leetcode.com/problems/merge-k-sorted-lists/)

This is my [solution](https://github.com/gzc/leetcode/blob/master/cpp/021-030/Merge%20k%20Sorted%20Lists%20.cpp)


***
Follow [@louis1992](https://github.com/gzc) on github to help finish this task.

Expand Down
64 changes: 64 additions & 0 deletions C06-Heapsort/d-ary-heaps.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*************************************************************************
> File Name: d-ary-heaps.cpp
> Author: Louis1992
> Mail: [email protected]
> Blog: http://gzc.github.io
> Created Time: Tue Jun 23 19:22:21 2015
************************************************************************/
#include<iostream>
#include<cstdio>
#include<climits>
using namespace std;

#define PARENT(i,d) ((i - 1) / d)
#define CHILD(i,c,d) (3 * i + c + 1)

typedef struct {
int *elements;
int d;
int heap_size;
} heap_t;

void max_heapify(heap_t *heap, int i) {
int largest = i;
int basechild = CHILD(i, 0, heap->d);

for (int k = 0; k < heap->d; k++) {
int child = basechild+k;
if (child < heap->heap_size && heap->elements[child] > heap->elements[largest])
largest = child;
}

if (largest != i) {
swap(heap->elements[i],heap->elements[largest]);
max_heapify(heap, largest);
}
}

int extract_max(heap_t *heap) {
int max = heap->elements[0];
heap->elements[0] = heap->elements[heap->heap_size - 1];
heap->heap_size--;
max_heapify(heap, 0);
return max;
};

void increase_key(heap_t *heap, int i, int key) {
if (key < heap->elements[i]) {
cerr << "new key is smaller than current key" << endl;
exit(-1);
}

while (i > 0 && heap->elements[PARENT(i,heap->d)] < key) {
heap->elements[i] = heap->elements[PARENT(i,heap->d)];
i = PARENT(i,heap->d);
}

heap->elements[i] = key;
}

void insert(heap_t *heap, int key) {
heap->heap_size++;
heap->elements[heap->heap_size - 1] = INT_MIN;
increase_key(heap, heap->heap_size - 1, key);
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit b8046d1

Please sign in to comment.