[Introduction to algorithm]solution to Exercises 6.5-8

Exercises 6.5-8

Start example

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

/* * B: the result, one sorted list * A[1..k]: k sorted lists * n: the total number of elements */ K-WAY-MERGE(B, A[k], n) /* * T has a property list(T[i]), which is an integer representing the list where T[i] comes from */ create array T[k] and N[k] 1 for i <-- 1 to k 2 do T[i] <-- A[i][1] 3 N[i] <-- 1 4 BUILD-MIN-HEAP(T) 5 for i <-- 1 to n 6 do B[i] <-- T[1] 7 t <-- list(T[1]) 8 N[t] <-- N[t] + 1 9 if N[t] > length(A[t]) 10 then HEAP-DELETE(T, 1) 11 else T[1] <-- A[t][N[t]] 12 MIN-HEAPIFY(T, 1) 
time cost: O(k) + O(k) + O(n*lgk) = O(n*lgk)
loop invariant:
(1) At the start of each iteration of the 'for' loop of lines 5-12, B[1..i-1] contains the i-1 smallest elements of lists A[1..k], in sorted order.
(2) There is only one smallest element  of each list of A[1..k] in the min-heap T if the list is not empty. 

 

Initialization:  B[1..i-1] is empty, the trivial case,显然成立
Maintenance:  根据假设(2)由于小根堆T中的元素是由剩余非空list每个抽取最小元素组成,因此还没有拷贝到B的元素中的最小元素就在T中,即为T[1], 现把T[1]拷贝到B[i],又由于假设(1)因此下次循环时(i增加1后),B[1..i-1]含有所有输入链A[1..k]的前i-1个最小的元素,且是按递增序的,(1)成立。
在从T[1所在list删除最小元素(即T[1],第8行删除)后,如果该list为空(第9行)那么把T[1]从T中小根堆中删除(同时维护了小根堆的特性),(2)成立。如果该list不为空(第11行),那么把该list的最小元素加入到小根堆中,(2)仍然成立。
Termination: 循环结束时,i为n+1,B[1..n]中含有所有输入list的前n个最小元素,且已经排好序,即所有元素都按序放入到了B中。

 


你可能感兴趣的:(Algorithm,list,Integer,input,each,merge)