您的位置:首页 > 其它

多路归并排序 merge k sorted array, merge k sorted linked list

2012-10-07 04:40 316 查看
归并k个有序数组,merge k sorted array

归并k个有序链表,merge k sorted linked list

给定k个有序数组,每个长度都是n,把这k个数组归并成一个有序数组。例如:

Input:
k = 3, n =  4
arr[][] = { {1, 3, 5, 7},
{2, 4, 6, 8},
{0, 9, 10, 11}} ;

Output: 0 1 2 3 4 5 6 7 8 9 10 11

算法:

构建一个长度是n*k的空数组。
从k个数组中,取出每个数组的第一个元素,构建一个最小堆。
把最小堆的根结点的元素放入结果中,并记下根结点元素来自哪个数组。

删除最小堆的顶点元素。
如果那个数组不空,从那个数组取下一个元素,放入堆中。
维护最小堆。

1. Create an output array of
size n*k.

2. Create a min heap of size k and
insert 1st element in all the arrays into a the heap

3. Repeat following steps n*k times.

a) Get
minimum element from heap (minimum is always at root) and store it in output array.

b) Replace
heap root with next element from the array from which the element is extracted. If the array doesn’t have any more elements, then replace root with infinite. After replacing the root, heapify the tree.

算法详见:http://www.geeksforgeeks.org/merge-k-sorted-arrays/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: