## Java实现单向链表的归并排序 作者是 在线疯狂 发布于 2014年11月21日 在 Java, 他山之石, 数据结构.

``````merge_sort(list) {
split list into two halfs, say first and second ;
merge_sort(firstHalf);
merge_sort(secondHalf);
merge(firstHalf,secondHalf);
}
``````

``````// The main function
public Node merge_sort(Node head) {
if (head == null || head.next == null) {
}
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) {
dummyHead = new Node();
while (a != null && b != null) {
if (a.val <= b.val) {
curr.next = a;
a = a.next;
} else {
curr.next = b;
b = b.next;
}
curr = curr.next;
}
curr.next = (a == null) ? b : a;
}

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

``````public class Node {
public Node next;
public int val;
}
``````

Pingbacks已关闭。