defmergeSort(nums): iflen(nums) <= 1: return nums # devide mid = len(nums)//2 left = nums[:mid] right = nums[mid:] return mergeFunc(mergeSort(left),mergeSort(right))
defmergeFunc(left,right): # merge res = [] while left and right: if left[0] <= right[0]: res.append(left.pop(0)) else: res.append(right.pop(0)) res += left res += right
defsortList(head): ifnot head ornot head.next: return head # get mid of linked list slow = fast = head while fast and fast.nextand fast.next.next: slow = slow.next fast = fast.next.next # devide right = slow.next slow.next = None # merge defmergeFunc(head,right): dummy = ListNode() cur = dummy while head and right: if head.val <= right.val: cur.next = head head = head.next # cur = cur.next # cur.next = None else: cur.next = right right = right.next cur = cur.next cur.next = None if head: cur.next = head if right: cur.next = right return dummy.next
return mergeFunc(sortList(head),sortList(right))
(1) average cost time: T(n) = O(nlogn) (2) average cost space: S(n) = O(1) (3) in-place (4) stable (5) best T(n) = O(nlogn), worst T(n) = O(nlogn)
-------------End of blogThanks for your reading-------------