Reputation: 187
I have a problem with MergeSort in Python-3.x. This is that the algorithm does not do the sorting. What's my mistakes? Can you help me?
The code is:
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)
And the result is:
[6, 7, -1, 0, 5, 2, 3, 8]
[Finished in 0.2s]
Upvotes: 1
Views: 115
Reputation: 14918
How about print(mergeSort(L))
. It gives [-1, 0, 2, 3, 5, 6, 7, 8]
for me.
The problem with the following code is that L
is not even modified. The return value of mergeSort(L)
(presumably) gives you the sorted list.
L = [6,7,-1,0,5,2,3,8]
mergeSort(L)
print(L)
Upvotes: 2