我们使用Merge sort中的merge函数为2个数组(G和H)进行联接。数组是:
G = [3,5,8,9] , H = [1,2,5,7]
为了更好地理解,我还将添加合并功能代码:(来源:https://www.geeksforgeeks.org/python-program-for-merge-sort/)
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r- m
# create temp arrays
L = [0] * (n1)
R = [0] * (n2)
# Copy data to temp arrays L[] and R[]
for i in range(0 , n1):
L[i] = arr[l + i]
for j in range(0 , n2):
R[j] = arr[m + 1 + j]
# Merge the temp arrays back into arr[l..r]
i = 0 # Initial index of first subarray
j = 0 # Initial index of second subarray
k = l # Initial index of merged subarray
while i < n1 and j < n2 :
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Copy the remaining elements of L[], if there
# are any
while i < n1:
arr[k] = L[i]
i += 1
k += 1
# Copy the remaining elements of R[], if there
# are any
while j < n2:
arr[k] = R[j]
j += 1
k += 1
这是我的思考过程:
Compare 1: 3 VS 1 [1]
Compare 2: 3 VS 2 [1,2]
Compare 3: 3 VS 5 [1,2,3]
Compare 4: 5 VS 5 [1,2,3,5]
Compare 5: 8 VS 5 [1,2,3,5,5]
Compare 6: 8 VS 7 [1,2,3,5,5,7]
当循环结束时,我们将元素从第一个数组复制到最终数组。 因此,总的来说,我们有6个比较。但是,我的大学提供的答案是5,真的不知道为什么!
编辑: 当数组元素相等时,我们将它们都添加到新数组中并增加指向当前位置的变量。需要将类似以下内容添加到代码中:
if L[i] == R[j]:
arr[k] = L[i]
k += 1
arr[k] = R[j]
i += 1
j += 1