import random
import pretty_errors
def mergeSort(data, left, right):
if left < right:
middle = (left + right)/2
middle = int(middle)
mergeSort(data, left, middle)
mergeSort(data, middle+1, right)
merge(data, left, middle, right)
def merge(data, left, middle, right):
#额外集合,暂时存储有序数列
tmp = []
i = left
j = middle + 1
while i <= middle and j <= right:
if data[i] <= data[j]:
tmp.append(data[i])
i = i + 1
else:
tmp.append(data[j])
j = j + 1
#如果还有剩余,则直接加入集合
while i <= middle:
tmp.append(data[i])
i = i + 1
while j <= right:
tmp.append(data[j])
j = j + 1
k = 0
while k < len(tmp):
data[left+k] = tmp[k]
k = k + 1
#打印输出
def printf(data_p, state):
for i in state:
print(i, end = '')
print(":")
for i in data_p:
print(i, end = ' ')
print('\n')
def main():
data = []
for i in range(30):
data.append(random.randint(-1000, 1000))
printf(data, "raw data")
mergeSort(data, 0, len(data)-1)
printf(data, "sorted data")
if __name__ == '__main__':
main()