Created
October 5, 2014 06:53
-
-
Save prat0318/eed2ebed6877b7eab087 to your computer and use it in GitHub Desktop.
Merge sort a linked list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node(object): | |
def __init__(self, val): | |
self.val = val | |
self.next = None | |
def sort(head, tail=None): | |
if not head: | |
return None | |
if head.next == tail: | |
return head | |
slow = head; fast = head | |
prev_slow = None | |
while(fast and fast.next != tail): | |
prev_slow = slow | |
slow = slow.next | |
fast = fast.next.next | |
if prev_slow: | |
prev_slow.next = None | |
m = slow | |
left = sort(head, None) | |
right = sort(m, tail) | |
if(left.val < right.val): | |
head = left | |
left = left.next | |
else: | |
head = right | |
right = right.next | |
final_tail = head | |
while(left and right): | |
if left.val < right.val: | |
final_tail.next = left | |
left = left.next | |
else: | |
final_tail.next = right | |
right = right.next | |
final_tail = final_tail.next | |
if left: | |
final_tail.next = left | |
elif right: | |
final_tail.next = right | |
return head | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment