如何使用LinkedList实现合并排序?

时间:2015-12-06 10:19:43

标签: java mergesort

我正在尝试使用LinkedList实现合并排序,到目前为止,

class Node{


Node next;
int data;

public Node (){

}

public Node(int _data){

    this.data = _data;
   }
  }


 public  class myTest{

   private static Node head;
   private static Node current; 

   public void myTest(){

    this.head = null;
    this.current = null;
}

public static void insert( int data ){

    Node newNode = new Node(data);

    if (head == null){

        head = newNode;
        current = head;
    }

    else {

        current.next = newNode;
        current = newNode;
    }
}

public static void display(Node cur ){

    while( cur != null){

        if (cur.next != null){
            System.out.print(cur.data + " -> ");
        }

        else{
            System.out.print(cur.data +" ");
        }

        cur = cur.next;
    }

    System.out.println();
}

private static Node mergeSort(Node headOriginal ){

    if (headOriginal == null || headOriginal.next == null ){

        return headOriginal; 
    }

    Node a = headOriginal;
    Node b  = headOriginal.next;

    while( b != null && b.next != null ){

        headOriginal = headOriginal.next;
        b = (b.next).next;
    }

    // split in 2 parts 
    b = headOriginal.next;
    headOriginal.next = null;

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


 // sort among the 2 parts
 public static Node merge(Node a, Node b) {

    Node c = new Node();
    Node head_1 = c;

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

        if ( a.data <= b.data ){

            c.next = a;
            c = a;
            a = a.next;
        }

        else {

            c.next = b;
            c = b;
            b = b.next;
        }
    }

    c.next = (a == null) ? b : a;
    return head_1.next;        
}  

public static void main(String[] args ){

    int [] arr = {12, 34, 5, 6, 7};

    for (int j =0; j < arr.length; j++){

        insert( arr[j] );
    }

    mergeSort(head);
    display(head);

  }
}

mergeSort 函数获取从 插入 函数生成的LikedList的原始头部。我相信该函数正确创建了一个按升序排序的LL。 显示 功能假设打印LL。在这种情况下,它仅从原始头部(12)打印到分类的LL的末尾并打印'12 - > 34'。我假设如果我可以通过新创建的排序LL的头部,它将能够打印整个排序的LL。

  1. 我的程序是否正常,或者需要一些改进才能实现合并排序?
  2. 如何让已排序的LL的头部通过 显示 方法?

1 个答案:

答案 0 :(得分:0)

我想这是出于学术目的,因为Sandeep的评论是正确的,因为LinkedList不是mergesort的合适数据结构。编写自己的链表也可能不是一个好主意,因为Java API数据结构经过精心设计和测试!

但是对于你的代码,它工作得很好!唯一的错误是你没有使用mergesort的结果,而是你的“旧”引用。如果你更新你的参考,它应该没问题。尝试:

head = mergeSort(head);
display(head);

在您的main方法中,它应该按照需要工作!

相关问题