# coding:utf-8
# 下面是归并排序 中 出现的一些语法的错误
def MergeSort(array: [], startIndex: int, endIndex: int):
if startIndex >= endIndex:
return
# mid = (startIndex + endIndex)//2 +1
mid = startIndex + (endIndex - startIndex) // 2 #python // 才能表示整除 使用 / 会出现float类型
MergeSort(array, startIndex, mid)
MergeSort(array, mid + 1, endIndex)
Merge(array, startIndex, mid, endIndex)
def Merge(array: [], startIndex: int, mid: int, endIndex: int):
tempLi = []
# mid = startIndex + (endIndex - startIndex) / 2
# mid = (startIndex + endIndex) / 2
p = 0
p1 = startIndex
p2 = mid + 1
while p1 <= mid and p2 <= endIndex:
if array[p1] <= array[p2]:
tempLi.append(array[p1])
p += 1
p1 += 1
else:
tempLi.append(array[p2])
p += 1
p2 += 1
while p1 <= mid:
tempLi.append(array[p1])
# tempLi[p] = array[p1]
p += 1
p1 += 1
while p2 <= endIndex:
tempLi.append(array[p2])
#当tempLi为空的时候 ,不能通过下标来索引
# tempLi[p] = array[p2]
p += 1
p2 += 1
for i in range(0, tempLi.__len__()):
array[startIndex + i] = tempLi[i]
if __name__ == '__main__':
from random import randint
array = [randint(1, 10) for i in range(10)]
print(f"原来的:{array}")
MergeSort(array, 0, array.__len__() - 1)
print(f"现在的:{array}")