归并排序的基本思路是分治,把一个大问题分解成小问题。逐个解决小问题。 以长度的一半为基准点,将一个大列表分为两个小列表,一直分一直分,然后合并。 所以排序分为两步: 第一步是分解,第二步是合并。
(self, unsorted_list, key=None)
| 84 | |
| 85 | |
| 86 | def mergeSort(self, unsorted_list, key=None): |
| 87 | """ |
| 88 | 归并排序的基本思路是分治,把一个大问题分解成小问题。逐个解决小问题。 |
| 89 | 以长度的一半为基准点,将一个大列表分为两个小列表,一直分一直分,然后合并。 |
| 90 | 所以排序分为两步: |
| 91 | 第一步是分解,第二步是合并。 |
| 92 | """ |
| 93 | if len(unsorted_list) <= 1: |
| 94 | return unsorted_list |
| 95 | |
| 96 | break_point = len(unsorted_list) // 2 |
| 97 | |
| 98 | left = self.mergeSort(unsorted_list[:break_point]) |
| 99 | right = self.mergeSort(unsorted_list[break_point:]) |
| 100 | |
| 101 | return self._decomposeAndMerge(left, right, key=key) |
| 102 | |
| 103 | def _decomposeAndMerge(self, unsorted_list_A, unsorted_list_B, key): |
| 104 | sorted_list = [] |
nothing calls this directly
no test coverage detected