1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| def merge_sort(self, nums: List[int]): self.m_sort(nums, 0, len(nums) - 1)
def m_sort(self, nums: List[int], start: int, end: int): if start >= end: return mid = start + (end - start) // 2 self.m_sort(nums, start, mid) self.m_sort(nums, mid + 1, end) self.merge(nums, start, mid, end)
def merge(self, nums: List[int], start: int, mid: int, end: int): i, j, res = start, mid + 1, [] while i <= mid and j <= end: if nums[i] <= nums[j]: res.append(nums[i]) i += 1 else: res.append(nums[j]) j += 1 while i <= mid: res.append(nums[i]) i += 1 while j <= end: res.append(nums[j]) j += 1 nums[start:end + 1] = res
|