Exercises 6 - GEOCITIES.ws

Anuncio
Emiro Andres Ruiz Mesa
256994
Diana Marcela Velandia Vásquez
257005
INTRODUCTION TO ALGORITHMS
CLRS
Ejercicio 6.5-3
Write pseudocode for the procedures, that implement a min-priority queue with a min-heap.
HEAP-MINIMUM (A) //Retorna el valor mínimo del elemento en el heap
return A[1];
HEAP_EXTRACT_MIN (A) // Remueve y retorna el mínimo valor del elemento en el
heap
if heap_size[A] < 1 then mensaje de error
min = A[1]
A[1] =A[heap_size[A]]
heap_size[A] = heap_size[A] – 1
MIN_HEAPY (A , 1)
Return min
HEAP-DECREASE-KEY (A, i, key) //disminuye la prioridad de asociación entre los
elementos i y key
if key > A[i] then mensaje de error
A[i] = key;
while i>0 and A[Parent(i)] > A[i]
swap A[i] and A[Parent(i)]
i = Parent(i);
MIN_HEAP_INSERT (A, key)
heap_size[A] = heap_size[A] + 1 then mensaje de error
A[heap_size[A]] = largest integer
A[1] =A[heap_size[A]]
HEAP_DECREASE_KEY(A , Heap_size[A], key)
Exercises 6.5-8
Give an O(n lg k)-time algorithm to merge k sorted lists into one sorted list, where n is the
total number of elements in all the input lists. (Hint: Use a min-heap for k-way merging.)
Given k sorted lists with a total of n elements show how to merge them in O(n lg k) time.
Insert all k elements a position 1 from each list into a heap. Use EXTRACT-MAX to obtain
the _rst element of the merged list. Insert element at position 2 from the list where the
largest element originally came from into the heap. Continuing in this fashion yields the
desired algorithm. Clearly the running time is O(n lg k).
Problems 6-1:
Building a heap using insertion
The procedure BUILD-MAX-HEAP in Section 6.3 can be implemented by repeatedly using
MAX-HEAP-INSERT to insert the elements into the heap. Consider the following
implementation:
BUILD-MAX-HEAP'(A)
1 heap-size[A] ← 1
2 for i ← 2 to length[A]
3 do MAX-HEAP-INSERT(A, A[i])
a.
Do the procedures BUILD-MAX-HEAP and BUILD-MAX-HEAP' always create
the same heap when run on the same input array? Prove that they do, or provide a
counterexample.
Build-Max-Heap (A)
1. heap-size (A) = length (A)
2. for (i = floor[length (A)/ 2] ;i > 0 ;i --)
(a) do Max-Heapify (A,i)
b. Show that in the worst case, BUILD-MAX-HEAP' requires Θ(n lg n) time to build
an n-element heap.
A top level of time O(nlg n) is obtained immediately of doing n-1 calls to
MAX HEAP INSERT, each one takes time of O(lgn). For a low level of O(n lg
n), we consider the case in which the arrangement of this entry given in
strictly incremental order. Every call to MAX HEAP INSERT causes that
HEAP WAS UNCREATING KEY cross all the way up to the root. Of this the
depth of the node i is
lg i , the total time is:
In the worst case, therefore, BUILD MAX HEAP 'it needs time of
construct a heap of n elements.
(n lg n)to
Descargar