My algorithm works perfectly for an array of up to 10^6 elements, even though it is not that efficient it does it's job. The array which I want it to be sorted is randomly generated. I read from a file the number of elements the array will have and the maximum value and then create the list.
def mergeSort(listaNumere):
n = len(listaNumere)
if n == 1:
return listaNumere
mij = n//2
stanga = []
for i in range (0, mij):
stanga.append(listaNumere[i])
dreapta = []
for i in range(mij, n):
dreapta.append(listaNumere[i])
#stanga = listaNumere[:mij]
#dreapta = listaNumere[mij:]
stanga = mergeSort(stanga)
dreapta = mergeSort(dreapta)
return merge(stanga, dreapta)
def merge(stanga, dreapta):
aux = []
while len(stanga) != 0 and len(dreapta) != 0:
if stanga[0] < dreapta[0]:
aux.append(stanga[0])
del stanga[0]
else:
aux.append(dreapta[0])
del dreapta[0]
while len(stanga) != 0:
aux.append(stanga[0])
del stanga[0]
while len(dreapta) != 0:
aux.append(dreapta[0])
del dreapta[0]
return aux
The program has been running in the background for the past 30 minutes and has not finished sorting the array.
How can i make the program more efficient so that it does not take that much time to run?
Tried this:
def merge(stanga, dreapta):
aux = []
i,j = 0,0
while i < len(stanga) and j < len(dreapta):
if stanga[i] < dreapta[j]:
aux.append(stanga[i])
i += 1
else:
aux.append(dreapta[j])
j += 1
while i < len(stanga):
aux.append(stanga[i])
i += 1
while j < len(dreapta):
aux.append(dreapta[i])
i += 1
return aux