【发布时间】: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