INFO-MPx-2021/Tritritritri .py

112 lines
2.6 KiB
Python

import numpy as np
tl = (np.array(np.random.rand(20)*100,dtype=int))
def triInsertion(l):
out = []
for e in l:
toadd = e
nout = []
for i in range(len(out)):
if out[i]>=toadd:
nout.append(toadd)
toadd=out[i]
else:
nout.append(out[i])
nout.append(toadd)
out = nout
return out
def triFusionRec(l):
if len(l)==0:
return l
if len(l)==1:
return l
n = len(l)//2
l1,l2 = triFusionRec(l[:n]),triFusionRec(l[n:])
out = []
i,j = 0,0
while i<len(l1) or j<len(l2):
if j>=len(l2) or (i<len(l1) and l1[i]<=l2[j]):
out.append(l1[i])
i+=1
else:
out.append(l2[j])
j+=1
return out
def triRapideRec(l):
if len(l)==0:
return l
if len(l)==1:
return l
n = np.random.randint(0,len(l))
pivo = l[n]
epivot,pppivot,pgpivot = [],[],[]
for e in l:
if e==pivo:
epivot.append(e)
elif e<pivo:
pppivot.append(e)
else:
pgpivot.append(e)
return triRapideRec(pppivot)+epivot+triRapideRec(pgpivot)
def triRapideEnPlace(l,a=None,b=None):
"""
Trie la liste l entre a et b
"""
if a==None: a = 0
if b==None: b = len(l)
if b-a==0:
return l
if b-a==1:
return l
n = a+(b-a)//2
pivot = l[n]
i = n
maxindex = b
minindex = a
while maxindex != minindex:
# On souhaite ranger l'élément i dans la bonne moitié
# On suppose que i n'est pas dans les parties rangées
if l[i] < pivot or (l[i]==pivot and np.random.randint(0,2)==1):
l[i],l[minindex] = l[minindex],l[i]
minindex += 1
else:
l[i],l[maxindex-1] = l[maxindex-1],l[i]
maxindex -= 1
# On prend un i pas dans les parties triées
i = (maxindex-minindex)//2 + minindex
l = triRapideEnPlace(l,a,maxindex)
l = triRapideEnPlace(l,maxindex,b)
return l
def triFusionEnPlace(l,a=None,b=None):
"""
Trie la liste l entre a et b
"""
if a==None: a = 0
if b==None: b = len(l)
if b-a==0:
return l
if b-a==1:
return l
n = a + (b-a)//2
l = triFusionEnPlace(l,a,n)
l = triFusionEnPlace(l,n,b)
i = a
j = n
midmax = l[n-1]
while i<n-a and j<b-n
def multitest():
for _ in range(1000):
tl = (np.array(np.random.rand(20)*100,dtype=int))
print(tl)
assert (triInsertion(tl)==triRapideEnPlace(tl)).all()