【问题标题】:k-way merge with divide and conquer?k-way合并与分而治之?
【发布时间】:2012-09-08 17:29:10
【问题描述】:

这个想法是递归地合并第一个 k/2 个列表和第二个 k/2 个列表,然后将两个合并的列表合并为一个列表并返回。

我对递归合并第一个 k/2 与第二个 k/2 列表意味着什么感到困惑。 任何人都可以澄清这一点,或者查看一些解释这种递归的伪代码吗?

【问题讨论】:

  • 多一点上下文会很有用。整个算法在做什么?
  • 家庭作业?有趣的措辞——k-way 和 2-way 合二为一。不用担心被混淆;我认为“想法”也很混乱。

标签: algorithm divide-and-conquer


【解决方案1】:
List recursiveMerge(List[] lists)
{
  // Easy to solve problem for up to length 2
  if (lists.length < 1)
  {
    return new List();
  }
  if (lists.length == 1)
  {
    return lists[0];
  }
  if (lists.length == 2)
  {
    return baseMerge(lists[0], lists[1]);
  }
  // For longer lengths split the array into two
  int half = lists.length / 2;
  List[] firstHalf = new List[half];
  List[] secondHalf = new List[lists.length - half];
  System.arraycopy(lists, 0, firstHalf, 0, firstHalf.length);
  System.arraycopy(lists, firstHalf.length, secondHalf,
    0, secondHalf.length);
  // Solve the problem separately in each sub-array
  List a = recursiveMerge(firstHalf);
  List b = recursiveMerge(secondHalf);
  // and produce a combined solution
  return baseMerge(a, b);
}

如果您从 N 个列表 0,1,2,3... 开始,那么在递归树的底部,我们将 0 与 1 合并,将 2 与 3 合并,将 4 与 5 合并,以此类推。下一步将 0+1 与 2+3 合并,将 4+5 与 6+7 合并,以此类推。因此,如果有 N 个列表,则树中有 lg(N) 个级别,每个级别处理每个数据点一次。因此,如果有 N 个总长度为 L 的列表,则成本为 O(L log(N))。

【讨论】:

  • 你能解释一下这个算法的时间复杂度吗?
  • 不会是 O(N L log(N)) - 因为在递归中你复制了 O(N L) 数组的每一半?
  • 总长度 L 我的意思是 L 是所有列表长度的总和
猜你喜欢
  • 2013-02-05
  • 1970-01-01
  • 2013-11-09
  • 2018-08-24
  • 2016-04-04
  • 2012-02-25
  • 2014-12-05
  • 2016-02-05
  • 1970-01-01
相关资源
最近更新 更多