I'd like this code reviewed.
import java.util.NoSuchElementException;
public class MergeSort {
private Node first;
private Node last;
private static class Node {
int element;
Node next;
Node(int element, Node node) {
this.element = element;
this.next = node;
}
}
public void displayList() {
Node tempFirst = first;
while (tempFirst != null) {
System.out.print(tempFirst.element + " ");
tempFirst = tempFirst.next;
}
}
public void add (int val) {
final Node l = last;
final Node newNode = new Node(val, null);
last = newNode;
if (first == null) {
first = newNode;
} else {
l.next = newNode;
}
}
public void sort() {
/**
* QQ: should there be an exception check for last == null also ?
*/
if (first == null) {
throw new NoSuchElementException("The linkedlist doesnot contain any node.");
}
first = divide(first, last);
}
private Node getMidPoint(Node node) {
assert node != null;
Node fast = node.next;
Node slow = node;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private Node divide(Node node1, Node node2) {
if (node1 == node2) return node1;
Node midPoint = getMidPoint(node1);
Node midpointNext = midPoint.next;
midPoint.next = null;
Node n1 = divide(node1, midPoint);
Node n2 = divide(midpointNext, node2);
return mergeLinkedList(n1, n2);
}
private Node mergeLinkedList(Node node1, Node node2) {
assert node1 != null;
assert node2 != null;
Node current = null;
Node currentHead = null;
while (node1 != null && node2 != null) {
if (node1.element < node2.element) {
if (current == null) {
currentHead = node1;
current = node1;
} else {
current.next = node1;
current = current.next;
}
node1 = node1.next;
} else {
if (current == null) {
currentHead = node2;
current = node2;
} else {
current.next = node2;
current = current.next;
}
node2 = node2.next;
}
}
current.next = node1 != null ? node1 : node2;
return currentHead;
}
public static void main(String args[]) {
// odd size list
MergeSort ms1 = new MergeSort();
int[] a1 = {5, 4, 3, 2, 1};
for (int i : a1) {
ms1.add(i);
}
ms1.sort();
ms1.displayList();
System.out.println();
// even size list.
MergeSort ms2 = new MergeSort();
int[] a2 = {5, 4, 3, 2};
for (int i : a2) {
ms2.add(i);
}
ms2.sort();
ms2.displayList();
System.out.println();
// list of size 1
MergeSort ms3 = new MergeSort();
int[] a3 = {1};
for (int i : a3) {
ms3.add(i);
}
ms3.sort();
ms3.displayList();
System.out.println();
// list of size 2
MergeSort ms4 = new MergeSort();
int[] a4 = {2, 1};
for (int i : a4) {
ms4.add(i);
}
ms4.sort();
ms4.displayList();
System.out.println();
}
}