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

本文介绍了一种算法,用于将k个长度为n的有序数组合并成一个有序数组,通过构建最小堆来实现高效的合并过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

归并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 
算法:

  1. 构建一个长度是n*k的空数组。
  2. 从k个数组中,取出每个数组的第一个元素,构建一个最小堆。
  3. 把最小堆的根结点的元素放入结果中,并记下根结点元素来自哪个数组。
    1. 删除最小堆的顶点元素。
    2. 如果那个数组不空,从那个数组取下一个元素,放入堆中。
    3. 维护最小堆。
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.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值