CommencerCommencer gratuitement

Tri de la sélection de la codification

Dans la dernière vidéo, vous avez étudié l'algorithme de tri par sélection.

Dans cet exercice, vous devrez la mettre en œuvre en complétant la fonction selection_sort().

Cet exercice fait partie du cours

Structures de données et algorithmes en Python

Afficher le cours

Instructions

  • Fixez lowest à l'élément de la liste situé à l'indice i.
  • Itérer à nouveau sur la liste en commençant par la position suivante de la variable i.
  • Comparez si l'élément de la liste situé à l'index j est plus petit que lowest.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

def selection_sort(my_list):
  list_length = len(my_list)
  for i in range(list_length - 1):
    # Set lowest to the element of the list located at index i
    lowest = ____
    index = i
    # Iterate again over the list starting on the next position of the i variable
    ____ j in range(____, list_length):
      # Compare whether the element of the list located at index j is smaller than lowest
      if _____:
        index = j
        lowest = my_list[j]
    my_list[i] , my_list[index] = my_list[index] , my_list[i]
  return my_list

my_list = [6, 2, 9, 7, 4, 8] 
selection_sort(my_list)
print(my_list)
Modifier et exécuter le code