xxxxxxxxxx
function Node(data) {
this.data = data === undefined ? null : data;
this.next = null;
}
function sortedMerge(first, second) {
let a = new Node()
const dummy = a
while(first && second ){
if( first.data <second.data){
a.next = first
first = first.next
}
else{
a.next= second
second= second.next
}
a= a.next
}
if(first){
a.next=first
}
if(second){
a.next = second
}
return dummy.next
}
xxxxxxxxxx
# Python3 program to merge sort of linked list
# create Node using class Node.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# push new value to linked list
# using append method
def append(self, new_value):
# Allocate new node
new_node = Node(new_value)
# if head is None, initialize it to new node
if self.head is None:
self.head = new_node
return
curr_node = self.head
while curr_node.next is not None:
curr_node = curr_node.next
# Append the new node at the end
# of the linked list
curr_node.next = new_node
def sortedMerge(self, a, b):
result = None
# Base cases
if a == None:
return b
if b == None:
return a
# pick either a or b and recur..
if a.data <= b.data:
result = a
result.next = self.sortedMerge(a.next, b)
else:
result = b
result.next = self.sortedMerge(a, b.next)
return result
def mergeSort(self, h):
# Base case if head is None
if h == None or h.next == None:
return h
# get the middle of the list
middle = self.getMiddle(h)
nexttomiddle = middle.next
# set the next of middle node to None
middle.next = None
# Apply mergeSort on left list
left = self.mergeSort(h)
# Apply mergeSort on right list
right = self.mergeSort(nexttomiddle)
# Merge the left and right lists
sortedlist = self.sortedMerge(left, right)
return sortedlist
# Utility function to get the middle
# of the linked list
def getMiddle(self, head):
if (head == None):
return head
slow = head
fast = head
while (fast.next != None and
fast.next.next != None):
slow = slow.next
fast = fast.next.next
return slow
# Utility function to print the linked list
def printList(head):
if head is None:
print(' ')
return
curr_node = head
while curr_node:
print(curr_node.data, end = " ")
curr_node = curr_node.next
print(' ')
# Driver Code
if __name__ == '__main__':
li = LinkedList()
# Let us create a unsorted linked list
# to test the functions created.
# The list shall be a: 2->3->20->5->10->15
li.append(15)
li.append(10)
li.append(5)
li.append(20)
li.append(3)
li.append(2)
# Apply merge Sort
li.head = li.mergeSort(li.head)
print ("Sorted Linked List is:")
printList(li.head)
# This code is contributed by Vikas Chitturi
xxxxxxxxxx
class ListNode {
val: number
next: ListNode | null
constructor(val?: number, next?: ListNode | null) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
}
function mergeTwoLists(list1: ListNode | null, list2: ListNode | null): ListNode | null {
if (!list1) return list2
if (!list2) return list1
if (!list1 && !list2) return null
let sorted = new ListNode(), current = sorted
while (list1 && list2) {
if (list1.val < list2.val) {
current.next = list1;
list1 = list1.next
} else {
current.next = list2
list2 = list2.next
}
current = current.next
}
current.next = list1 || list2
return sorted.next
};
xxxxxxxxxx
def merge_sort(linked_list):
"""
Sorts a linked list in ascending order
- Recursively divide the linked list into sublists containing a single node
- Repeatedly merge the sublists to produce sorted sublists until one remains
Returns a sorted linked list
Takes O(n log n) time
Takes O(n) space
"""
if linked_list.size() == 1:
return linked_list
elif linked_list.head is None:
return linked_list
left_half, right_half = split(linked_list)
left = merge_sort(left_half)
right = merge_sort(right_half)
return merge(left, right)
def split(linked_list):
"""
Divide the unsorted list at midpoint into sublists
Takes O(log n) time
"""
if linked_list == None or linked_list.head == None:
left_half = linked_list
right_half = None
return left_half, right_half
else:
size = linked_list.size()
mid = size//2
mid_node = linked_list.node_at_index(mid-1)
left_half = linked_list
right_half = LinkedList()
right_half.head = mid_node.next_node
mid_node.next_node = None
return left_half, right_half
def merge(left, right):
"""
Merges two linked lists, sorting by data in nodes
Returns a new merged list
Takes O(n) space
Runs in O(n) time
"""
# Create a new linked list that contains nodes from merging left and right
merged = LinkedList()
# Add a fake head that is discarded later.
merged.add(0)
# Set current to the head of the linked list
current = merged.head
# Obtain head nodes for left and right linked lists
left_head = left.head
right_head = right.head
# Iterate over left and right as long until the tail node of both
# left and right
while left_head or right_head:
# If the head node of left is None, we're at the tail
# Add the tail node from right to the merged linked list
if left_head is None:
current.next_node = right_head
# Call next on right to set loop condition to False
right_head = right_head.next_node
# If the head node of right is None, we're at the tail
# Add the tail node from left to the merged linked list
elif right_head is None:
current.next_node = left_head
# Call next on left to set loop condition to False
left_head = left_head.next_node
else:
# Not at either tail node
# Obtain node data to perform comparison operations
left_data = left_head.data
right_data = right_head.data
# If data on left is lesser than right set current to left node
# Move left head to next node
if left_data < right_data:
current.next_node = left_head
left_head = left_head.next_node
# If data on left is greater than right set current to right node
# Move right head to next node
else:
current.next_node = right_head
right_head = right_head.next_node
# Move current to next node
current = current.next_node
# Discard fake head and set first merged node as head
head = merged.head.next_node
merged.head = head
return merged