Začněte nyníZačněte zdarma

Implementace algoritmu quicksort

V tomto cvičení implementuješ algoritmus quicksort pro seřazení seznamu čísel.

V prvním kroku implementuješ funkci partition(), která vrátí index pivotu poté, co zpracuje seznam čísel tak, aby všechny prvky nalevo od pivotu byly menší než pivot a všechny prvky napravo od pivotu byly větší než pivot.

Ve druhém kroku implementuješ funkci quicksort(), která bude volat funkci partition().

Toto cvičení je součástí kurzu

Datové struktury a algoritmy v Pythonu

Zobrazit kurz

Interaktivní cvičení na vyzkoušení si v praxi

Vyzkoušejte si toto cvičení dokončením tohoto ukázkového kódu.

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
Upravit a spustit kód