Don*_*hoi 3 python sorting merge mergesort python-3.x
我正在制作合并排序代码,但它没有排序.你看到它有什么问题吗?
def mergeSort(L):
if len(L) == 1:
return L
else:
# divide
L1 = mergeSort(L[0:round(len(L)/2)])
L2 = mergeSort(L[round(len(L)/2):len(L)])
# merge
i = 0
j = 0
K = []
while i < len(L1) and j < len(L2):
if L1[i] < L2[j]:
K.append(L1[i])
i=i+1
else:
K.append(L2[j])
j=j+1
return K
Run Code Online (Sandbox Code Playgroud)
输入:
L = [1,2,5,7,8,0,10,21,32,53,16,16,48,59,64,53,75,52,42,21,98,76??]
Run Code Online (Sandbox Code Playgroud)
输出:
L = [0]
Run Code Online (Sandbox Code Playgroud)
while i < len(L1) and j < len(L2):
Run Code Online (Sandbox Code Playgroud)
这对我来说不合适.在这种情况下,一旦i或j到达各自列表的末尾,循环将结束.因此,可能仍然存在其他列表中永远不会迭代的元素.
尝试将其更改and
为a or
,并添加一些检查以确保只有当列表尚未完全迭代时才会发生列表间比较:
while i < len(L1) or j < len(L2):
if i < len(L1) and (j == len(L2) or L1[i] < L2[j]):
K.append(L1[i])
i=i+1
else:
K.append(L2[j])
j=j+1
Run Code Online (Sandbox Code Playgroud)
现在您的代码输出[0, 1, 2, 5, 7, 8, 10, 16, 16, 21, 21, 32, 42, 48, 52, 53, 53, 59, 64, 75, 76, 98]
.
归档时间: |
|
查看次数: |
45 次 |
最近记录: |