2012-09-15 96 views
1

这个想法是将第一个k/2列表和第二个k/2列表进行递归合并,然后将两个合并列表合并到一个列表中并返回。k-way与分而治之合并?

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

+0

多一点上下文会有用。整个算法在做什么? –

+0

作业?有趣的措辞 - k-way和2-way在一个。不要担心会感到困惑;我认为这个“想法”也很混乱。 –

回答

2
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); 
}