Zacznij terazZacznij za darmo

Kodowanie sortowania przez wybieranie

W ostatnim filmie poznałeś algorytm sortowania przez wybieranie (selection sort).

W tym ćwiczeniu zaimplementujesz go, uzupełniając funkcję selection_sort().

To ćwiczenie jest częścią kursu

Struktury danych i algorytmy w Pythonie

Zobacz kurs

Instrukcje do ćwiczenia

  • Przypisz do lowest element listy znajdujący się pod indeksem i.
  • Ponownie iteruj po liście, zaczynając od kolejnej pozycji zmiennej i.
  • Sprawdź, czy element listy pod indeksem j jest mniejszy niż lowest.

Interaktywne ćwiczenie praktyczne

Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.

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)
Edytuj i uruchom kod