您的位置:首页 > 其它

Merge Sort Array --> Merge Sort Linked List --> Insertion Sort Array --> Insertion sort Linked List

2014-12-11 16:25 459 查看
Merge Sort Array:

/*
* Merge Sort
*/
private void MergeSort(int[] array) {
if(array == null || array.length <=1) return;
mergeSort(array, 0, array.length -1);
}

private void mergeSort(int[] array, int start, int end){
if(start < end){
int mid = start + (end-start)/2;
mergeSort(array, start, mid);
mergeSort(array, mid+1, end);
merge(array, start, mid, end);
}
}

private void merge(int[] array, int start, int mid, int end) {
int[] helper = new int[array.length];
for(int i=0; i<array.length; i++){
helper[i] = array[i];
}

// scan helper array, and copy the smaller value one by one into original array;
int left = start;
int right = mid+1;
int current = start;
while(left<=mid && right<=end){
if(helper[left] < helper[right]){
array[current] = helper[left];
current++;
left++;
} else {
array[current] = helper[right];
current++;
right++;
}
}

while(left<=mid){
array[current] = helper[left];
current++;
left++;
}
}

Sort a linked list in O(n log n)
time using constant space complexity.

思路:merge sort 是nlogn

注意: 1.
分开两个list,找中点的时候,要找中点的前一个点,因为前面的list最后一个需要变成null,跟后面分开。所以:while( runner.next != null && runner.next.next != null) 这样就是cur是中点的前一个点。

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; }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode slow = head;
        ListNode fast = head;
        while(fast!=null && fast.next!= null && fast.next.next!= null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode newhead = slow.next;
        slow.next = null;
        ListNode l1 = sortList(head);
        ListNode l2 = sortList(newhead);
        return merge(l1, l2);
    }
     
    public ListNode merge(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        ListNode dump = new ListNode(0);
        ListNod
bebb
e cur = dump;
        while(l1 != null && l2 != null) {
            ListNode l1next = l1.next;
            ListNode l2next = l2.next;
             
            if(l1.val < l2.val) {
                cur.next = l1;
                l1.next = null;
                cur = l1;
                l1 = l1next;
            } else {
                cur.next = l2;
                l2.next = null;
                cur = l2;
                l2 = l2next;
            }
        }
        if(l1!=null) {
            cur.next = l1;
        }
        if(l2!=null) {
            cur.next = l2;
        }
        return dump.next;
    }
}

3. 这题再联想到:如何用 insertion sort 去sort integer array和 linked list
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: