Merge Sort Array: 看完stanford的 CS106B的video,https://www.youtube.com/watch?v=LlNawf0JeF0&list=PLnfg8b9vdpLn9exZweTJx44CII1bYczuk&index=55 醍醐灌顶;
public class Solution {
/**
* @param A: an integer array
* @return: nothing
*/
public void sortIntegers2(int[] A) {
// merge sort;
if(A == null || A.length == 0) return;
int[] temp = new int[A.length];
mergeSort(A, 0, A.length-1, temp);
}
private void mergeSort(int[] A, int start, int end, int[] temp) {
if(start >= end) {
return;
}
int mid = start + (end - start) / 2;
mergeSort(A, start, mid, temp);
mergeSort(A, mid+1, end, temp);
merge(A, start, end, temp);
}
private void merge(int[] A, int start, int end, int[] temp) {
int mid = start + (end - start) / 2;
int astart = start;
int bstart = mid+1;
int index = astart; // NOTE: index is astart;
while(astart <= mid && bstart <= end) {
if(A[astart] < A[bstart]) {
temp[index++] = A[astart++];
} else { // A[bstart] < A[astart];
temp[index++] = A[bstart++];
}
}
while(astart <= mid) {
temp[index++] = A[astart++];
}
while(bstart <= end) {
temp[index++] = A[bstart++];
}
// give temp to A;
for(int i=start; i<=end; i++){
A[i] = temp[i];
}
}
}
Merge Sort LinkedList:
Sort a linked list in O(n log n) time using constant space complexity.
思路:merge sort 是nlogn
注意:
1. 分开两个list,找中点的时候,一般是找中点的前一个点,因为前面的list最后一个需要变成null,跟后面分开。
2. merge的时候,为了返回head node必须有个dump,hold住head,然后有个cur作为指针,连接下一个node。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
private ListNode findMiddle(ListNode node) {
ListNode dummpy = new ListNode(0);
dummpy.next = node;
ListNode slow = dummpy;
ListNode fast = dummpy;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode slow = findMiddle(head);
ListNode newhead = slow.next;
slow.next = null;
ListNode l1 = sortList(head);
ListNode l2 = sortList(newhead);
return MergeTwoSortedList(l1, l2);
}
private ListNode MergeTwoSortedList(ListNode l1, ListNode l2) {
ListNode dummpy = new ListNode(0);
ListNode cur = dummpy;
while(l1 != null && l2 != null) {
if(l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
cur = cur.next;
} else {
cur.next = l2;
l2 = l2.next;
cur = cur.next;
}
}
if(l1 != null) {
cur.next = l1;
}
if(l2 != null) {
cur.next = l2;
}
return dummpy.next;
}
}
3. 这题再联想到:如何用 insertion sort 去sort integer array和 linked list