为什么这个合并排序函数不会导致无限循环?

时间:2015-12-05 04:35:37

标签: java sorting merge mergesort

我正在处理一个项目,该项目要求我在链接列表上实现合并排序,并且我正在使用此帖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;
}

1 个答案:

答案 0 :(得分:1)

这是因为上一行:

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

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

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

有一次,它会达到head.next == null条件。