【问题标题】:Why doesn't this merge-sort function cause an infinite loop?为什么这个合并排序函数不会导致无限循环?
【发布时间】:2016-03-10 03:39:25
【问题描述】:

我正在做一个需要我在链表上实现合并排序的项目,我正在使用这篇文章 Here 中的代码来帮助我。有人可以解释为什么在第 6 行,当我在其中调用 return merge(merge_sort(head),merge_sort(sHalf)); 方法 merge_sort(head) 时,它包含相同的头指针不会导致无限循环?在我看来,它正在以相同的头指针重新开始。

public Node merge_sort(Node head) {
    if(head == null || head.next == null) { return head; }
    Node middle = getMiddle(head);      //get the middle of the list
    Node sHalf = middle.next; middle.next = null;   //split the list into two               halfs

    return merge(merge_sort(head),merge_sort(sHalf));  //recurse on that
}

//Merge subroutine to merge two sorted lists
public Node merge(Node a, Node b) {
    Node dummyHead, curr; dummyHead = new Node(); curr = dummyHead;
    while(a !=null && b!= null) {
        if(a.info <= b.info) { curr.next = a; a = a.next; }
        else { curr.next = b; b = b.next; }
        curr = curr.next;
    }
    curr.next = (a == null) ? b : a;
    return dummyHead.next;
}

//Finding the middle element of the list for splitting
public Node getMiddle(Node head) {
    if(head == null) { return head; }
    Node slow, fast; slow = fast = head;
    while(fast.next != null && fast.next.next != null) {
        slow = slow.next; fast = fast.next.next;
    }
    return slow;
}

【问题讨论】:

  • 另一种自底向上排序链接列表的方法,比扫描列表拆分它们更简单快捷。 Wiki 有一个类似于 std::list::sort 中使用的示例。它使用与代码中相同的合并功能。 bottom merge sort for lists

标签: java sorting merge mergesort


【解决方案1】:

是因为上一行:

Node sHalf = middle.next; middle.next = null;

具体来说,middle.next = null; 部分。

了解即使头指针相同,我们将列表分成两半,使用middle.next = null。因此,在下一次递归调用中,它只是最初发送的链表的一半。

在某一时刻,它会达到head.next == null 条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 2011-08-13
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多