Mergesort与单链表

时间:2018-04-02 10:17:34

标签: java algorithm mergesort

我尝试在单链表的帮助下编写合并排序,下面提供了节点定义,

public class Node {

    public int item;
    public Node next;

    public Node(int val) {
        this.item = val;
    }

    public Node() {

    }

    @Override
    public String toString() {
        return "Node{" +
                "item=" + item +
                ", next=" + next +
                '}';
    }
}

合并排序的工作原理如下:

我。将未排序的列表分成n个子列表,每个子列表包含1个元素(1个元素的列表被视为已排序)。

II。重复合并子列表以生成新排序的子列表,直到只剩下1个子列表。这将是排序列表。代码如下所示。

public class MergesortWithSinglyLL {

    private Node head;

    public MergesortWithSinglyLL() {
        head = null;
    }

    public boolean isEmpty() {
        return (head == null);
    }

    public void insert(int val) {

        Node newNode = new Node(val);

        newNode.next = head;
        head = newNode;
    }

    // get the end of the queue
    public Node getHead() {
        return head;
    }


    /*
     Initially, this method is called recursively till there will be only one node
     */

    // this mergeSort returns the head of the sorted LL
    public Node mergeSort(Node head) {

        /*
            list is null or just one node is prevail
         */
        if (head == null || head.next == null) {
            return head;
        }

        Node a = head;
        Node b = head.next;

        while ((b != null) && (b.next != null)) {
            head = head.next;
            b = (b.next).next;
        }

        b = head.next;

        // split the list in 2 parts now
        head.next = null;

        return merge(mergeSort(a), mergeSort(b));
    }

    // This is the merge method provided.

    public Node merge(Node a, Node b) {

        Node head = new Node();
        Node c = head;

        while ((a != null) && (b != null)) {

            if (a.item <= b.item) {
                c.next = a;
//                c = a;
                c = c.next;
                a = a.next;
            } else {
                c.next = b;
//                c = b;
                c = c.next;
                b = b.next;
            }
        }

        // define the last element of the ll
        c.next = (a == null) ? b : a;
        return head.next;
    }


    public void display() {

        Node current = head;
        String result = "";

        while (current != null) {
            result += " " + current.item + " ";
            current = current.next;
        }
        System.out.println(result);
    }
}

我像这样进行发起呼叫,

    int[] arr = {12, 3, 4, 56, -7, -6, -5, 1};

    MergesortWithSinglyLL merges = new MergesortWithSinglyLL();

    for (int i = 0; i < arr.length; i++) {
        merges.insert(arr[i]);
    }

    merges.mergeSort(merges.getHead());
    merges.display();

结果是3 4 12 56,似乎所有负值都消失了。这是什么问题?

1 个答案:

答案 0 :(得分:4)

您的实施很好,错误在您称之为启动呼叫。

mergeSort会返回已排序的列表,但您不会对其进行分配,因此最终会得到解决方案的一个子集。

如果替换此行

ID

这一行

merges.mergeSort(merges.getHead());

(当然,你必须让MergesortWithSinglyLL.head公开)

您将看到您获得了正确的排序列表。