# merge_sort.py
from collections import deque
from typing import List
class Record:
def __init__(self, key):
self.key = key
self.other_info = None
class Records:
def __init__(self, record_list: List[Record]):
self.record_list = deque([None])
self.record_list.extend(record_list)
self.record_len = len(self.record_list)-1
self.other_info = None
def merge(records: Records, low, mid, high, temp_records: Records):
i = low
j = mid + 1
k = low
while i <= mid and j <= high:
if records.record_list[i].key <= records.record_list[j].key:
temp_records.record_list[k] = records.record_list[i]
i += 1
else:
temp_records.record_list[k] = records.record_list[j]
j += 1
k += 1
while i <= mid:
temp_records.record_list[k] = records.record_list[i]
i += 1
k += 1
while j <= high:
temp_records.record_list[k] = records.record_list[j]
j += 1
k += 1
for i in range(low, high+1): # 对records的更新
records.record_list[i] = temp_records.record_list[i]
def m_sort(records: Records, low, high, temp_records: Records):
if low < high:
mid = (low + high) >> 1
m_sort(records, low, mid, temp_records)
m_sort(records, mid + 1, high, temp_records)
merge(records, low, mid, high, temp_records)
def merge_sort(records: Records):
"""
2-路归并排序的初始调用过程
:param records:
:return:
"""
low = 1
high = records.record_len
temp_records = Records([None]*records.record_len) # 辅助记录列表对象
m_sort(records, low, high, temp_records)
return records
# test_merge_sort.py
from merge_sort import Record, Records, merge_sort
records = Records([Record(key) for key in [48, 62, 39, 77, 55, 14, 35, 98]])
records = merge_sort(records)
print([record.key for record in records.record_list if record])
"""
运行结果:
[14, 35, 39, 48, 55, 62, 77, 98]
Process finished with exit code 0
"""