归并排序与合并k个排序链表

一、归并排序

归并排序使用了分治法。以下代码按照《算法导论》实现,注意一点,这里的归并算法使用了一个“哨兵”来简化代码,即在每个堆末尾追加一个无穷大值,避免了每个步骤来检查要合并的两个堆是否为空。

public class Q23 {

    public static int max=Integer.MAX_VALUE;

    public void merge(int[] a,int p,int q,int r){
        int n1=q-p+1;
        int n2=r-q;
        int[] L=new int[n1+1];
        int[] R=new int[n2+1];
        for(int i=0;i

二、合并k个排序链表

归并排序与合并k个排序链表_第1张图片
利用归并排序的思想,代码如下:

public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0)
            return null;
        if (lists.length == 1)
            return lists[0];
        if (lists.length == 2)
            return mergelist(lists[0], lists[1]);

        int mid = lists.length / 2;
        
        ListNode[] listNodesr = new ListNode[mid];
        for (int i = 0; i < mid; i++) {
            listNodesr[i] = lists[i];
        }
        ListNode r = mergeKLists(listNodesr);

        ListNode[] listNodesl = new ListNode[lists.length - mid];
        for (int i = mid, j = 0; i < lists.length; i++, j++) {
            listNodesl[j] = lists[i];
        }
        ListNode l = mergeKLists(listNodesl);
        return mergelist(r, l);
    }

    public ListNode mergelist(ListNode r, ListNode l) {
        ListNode head = new ListNode(0);
        if (r == null && l == null)
            return null;
        else if (r == null) {
            return l;
        } else if (l == null) {
            return r;
        }
        if (l.val < r.val) {
            head.val = l.val;
            l = l.next;
        } else {
            head.val = r.val;
            r = r.next;
        }
        ListNode p = head;
        while (r != null && l != null) {
            if (r.val < l.val) {
                p.next = r;
                r = r.next;
            } else {
                p.next = l;
                l = l.next;
            }
            p = p.next;
        }
        while (l != null) {
            p.next = l;
            p = p.next;
            l = l.next;
        }
        while (r != null) {
            p.next = r;
            p = p.next;
            r = r.next;
        }
        return head;
    }

你可能感兴趣的:(算法)