我在 Python-3.x 中遇到合并排序问题。这是算法没有做排序。我的错误是什么?你能帮我吗?
代码是:
def mergeSort(lista):
#Precondición: elem comparables
#Postcondición: lista ordenada
if len(lista) < 2:
return lista
medio = len(lista) // 2
izq = mergeSort(lista[:medio])
der = mergeSort(lista[medio:])
return merge(izq,der)
def merge(lista1,lista2):
#Precondición: listas ordenadas
#Postcondición: retorna lista con elem de lista1 y lista2
i,j = 0,0
resultado = []
while i<len(lista1) and j<len(lista2):
if (lista1[i] < lista2[j]):
resultado.append(lista1[i])
i += 1
else:
resultado.append(lista2[j])
j += 1
resultado += lista1[i:]
resultado += lista2[j:]
return resultado
L = [6,7,-1,0,5,2,3,8]
mergeSort(L)
print(L)
结果是:
[6, 7, -1, 0, 5, 2, 3, 8]
[Finished in 0.2s]
最佳答案
怎么样print(mergeSort(L))
。它为我提供了 [-1, 0, 2, 3, 5, 6, 7, 8]
。
以下代码的问题是L
甚至没有被修改。 mergeSort(L)
的返回值(大概)为您提供排序后的列表。
L = [6,7,-1,0,5,2,3,8]
mergeSort(L)
print(L)
关于python - Python-3 中的归并排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46901669/