Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c2badc3

Browse files
author
Ram swaroop
committed
merge sort in linked list: optimized
1 parent 6a77d0d commit c2badc3

File tree

1 file changed

+6
-18
lines changed

1 file changed

+6
-18
lines changed

src/me/ramswaroop/linkedlists/MergeSort.java

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,10 @@ public static <E extends Comparable<E>> SingleLinkedNode<E> divideInTwoHalves(Si
5858
return slow;
5959
}
6060

61+
6162
/**
6263
* Merges two sorted lists starting at {@param node1} and {@param node2}
63-
* into one and returns its {@code head} reference.
64+
* into one and returns its starting node.
6465
* <p/>
6566
* This method is similar to {@link me.ramswaroop.linkedlists.MergeTwoSortedLists#mergeTwoSortedLists}
6667
*
@@ -75,21 +76,8 @@ public static <E extends Comparable<E>> SingleLinkedNode<E> mergeTwoSortedLists(
7576

7677
if (node1 == null && node2 == null) return null;
7778

78-
if (node1 == null) {
79-
head = node2;
80-
curr2 = curr2.next;
81-
} else if (node2 == null) {
82-
head = node1;
83-
curr1 = curr1.next;
84-
} else if (node1.item.compareTo(node2.item) < 0) {
85-
head = node1;
86-
curr1 = curr1.next;
87-
} else {
88-
head = node2;
89-
curr2 = curr2.next;
90-
}
79+
head = curr = new SingleLinkedNode<>(null); // dummy node
9180

92-
curr = head;
9381
while (curr1 != null || curr2 != null) {
9482
// handle cases where either of the list run out first
9583
if (curr1 == null) {
@@ -116,15 +104,15 @@ public static <E extends Comparable<E>> SingleLinkedNode<E> mergeTwoSortedLists(
116104
curr = curr.next;
117105
}
118106

119-
return head;
107+
return head.next;
120108
}
121109

122110
public static void main(String a[]) {
123111
SingleLinkedList<Integer> linkedList = new SingleLinkedList<>();
124-
linkedList.add(33);
125112
linkedList.add(21);
113+
linkedList.add(33);
126114
linkedList.add(89);
127-
linkedList.add(55);
115+
linkedList.add(21);
128116
linkedList.add(44);
129117
linkedList.add(67);
130118
linkedList.printList();

0 commit comments

Comments
 (0)