我一直在阅读排序算法。我遇到了合并排序的这段代码:
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
#function calls itself here<<<<<<<<<<<<<<<<<<<<<<<<<
mergeSort(L)# Sorting the first half
mergeSort(R)# Sorting the second half
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+= 1
else:
arr[k] = R[j]
j+= 1
k+= 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i+= 1
k+= 1
while j < len(R):
arr[k] = R[j]
j+= 1
k+= 1
# Code to print the list
def printList(arr):
for i in range(len(arr)):
print(arr[i], end =" ")
print()
# driver code to test the above code
if __name__ == '__main__':
#arr = [12, 11, 13, 5, 6, 7]
arr = [38, 27, 43, 3, 9, 82, 10]
print ("Given array is", end ="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end ="\n")
printList(arr)
# This code is contributed by Mayank Khanna
函数 mergeSort() 是从自身内部调用的,这是一个好的做法吗?我的印象是它可能会导致错误。
汪汪一只猫
喵喵时光机
相关分类