Écrire une fonction Python triant une liste par le principe de sélection du minimum.
On triera la liste sur place (pas de création de liste intermédiaire dans les étapes, et c'est la liste initiale qui est modifiée).
- un code possible
- avec traces
from random import randint # pour créer une liste au hasard
def indice_du_min(liste, depart):
"""
renvoie l'indice d'une valeur minimale
parmi liste[depart], liste[depart+1], liste[depart+2], ..., liste[len(liste)-1]
"""
valeur_min = liste[depart]
indice = depart
for i in range(depart+1, len(liste)):
if liste[i] < valeur_min :
valeur_min, indice = liste[i], i
return indice
def tri_selection(liste) :
for i in range(len(liste)-1):
m = indice_du_min(liste, i)
liste[i], liste[m] = liste[m], liste[i]
L = [randint(100,999) for i in range(randint(6,12))]
print("Liste avant le tri : ", L)
tri_selection(L)
print("\nListe après le tri : ", L)
Pour ceux qui aiment la concision :
from random import randint # pour créer une liste au hasard
def tri_selection(liste) :
for i in range(len(liste)-1):
m = min((liste[k], k) for k in range(i, len(liste)))[1]
liste[i], liste[m] = liste[m], liste[i]
L = [randint(100,999) for i in range(randint(6,12))]
print("Liste avant le tri : ", L)
tri_selection(L)
print("\nListe après le tri : ", L)
from random import randint # pour créer une liste au hasard
def indice_du_min(liste, depart):
"""
renvoie l'indice d'une valeur minimale
parmi liste[depart], liste[depart+1], liste[depart+2], ..., liste[len(liste)-1]
"""
valeur_min = liste[depart]
indice = depart
for i in range(depart+1, len(liste)):
if liste[i] < valeur_min :
valeur_min, indice = liste[i], i
return indice
def tri_selection(liste) :
for i in range(len(liste)-1):
m = indice_du_min(liste, i)
liste[i], liste[m] = liste[m], liste[i]
def tri_selection_avec_traces(liste):
for i in range(len(liste)-1):
m = indice_du_min(liste, i)
liste[i], liste[m] = liste[m], liste[i]
print("{} {}".format(liste[:i+1],liste[i+1:]))
L = [randint(100,999) for i in range(randint(6,12))]
print("Liste avant le tri : ", L)
print("\nEtapes du tri :" )
tri_selection_avec_traces(L)
print("\nListe après le tri : ", L)
On obtient par exemple :
Liste avant le tri : [781, 144, 699, 580, 912, 420, 993, 797, 112, 721, 355] Etapes du tri : [112] [144, 699, 580, 912, 420, 993, 797, 781, 721, 355] [112, 144] [699, 580, 912, 420, 993, 797, 781, 721, 355] [112, 144, 355] [580, 912, 420, 993, 797, 781, 721, 699] [112, 144, 355, 420] [912, 580, 993, 797, 781, 721, 699] [112, 144, 355, 420, 580] [912, 993, 797, 781, 721, 699] [112, 144, 355, 420, 580, 699] [993, 797, 781, 721, 912] [112, 144, 355, 420, 580, 699, 721] [797, 781, 993, 912] [112, 144, 355, 420, 580, 699, 721, 781] [797, 993, 912] [112, 144, 355, 420, 580, 699, 721, 781, 797] [993, 912] [112, 144, 355, 420, 580, 699, 721, 781, 797, 912] [993] Liste après le tri : [112, 144, 355, 420, 580, 699, 721, 781, 797, 912, 993]