Implementacja algorytmu quicksort
W tym ćwiczeniu zaimplementujesz algorytm quicksort do sortowania listy liczb.
W pierwszym kroku zaimplementujesz funkcję partition(), która zwraca indeks elementu podziału (pivot) po przetworzeniu listy liczb tak, aby wszystkie elementy po lewej stronie pivotu były od niego mniejsze, a wszystkie elementy po prawej – większe.
W drugim kroku zaimplementujesz funkcję quicksort(), która będzie wywoływać funkcję partition().
To ćwiczenie jest częścią kursu
Struktury danych i algorytmy w Pythonie
Interaktywne ćwiczenie praktyczne
Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.
def partition(my_list, first_index, last_index):
pivot = my_list[first_index]
left_pointer = first_index + 1
right_pointer = last_index
while True:
# Iterate until the value pointed by left_pointer is greater than pivot or left_pointer is greater than last_index
while ____ < ____ and ____ < ____:
left_pointer += 1
while my_list[right_pointer] > pivot and right_pointer >= first_index:
right_pointer -= 1
if left_pointer >= right_pointer:
break
# Swap the values for the elements located at the left_pointer and right_pointer
my_list[left_pointer], my_list[right_pointer] = ____, ____
my_list[first_index], my_list[right_pointer] = my_list[right_pointer], my_list[first_index]
return right_pointer