|
| 1 | +# Быстрая сортировка используя рекурсию. |
| 2 | +# ---------- |
| 3 | +# Quick sort using recursion. |
| 4 | + |
| 5 | + |
| 6 | +# Создаем функцию "quick_sort", которая принимает один входной параметр: |
| 7 | +# список "list_to_sort", который содержит числа. Эта функция возвращает отсортированный список по возрастанию. |
| 8 | +# ---------- |
| 9 | +# Create the function "quick_sort" that accepts one parameter: the list "list_to_sort" that contains the numbers. |
| 10 | +# This function returns the sorted list in ascending order. |
| 11 | +def quick_sort(list_to_sort): |
| 12 | + # Создаем базовый случай. |
| 13 | + # Базовый случай в рекурсивной функции - это часть кода функции, в которой описывается |
| 14 | + # условие прекращения работы функции в целях предотвращения зацикливания. |
| 15 | + # Если одна из вызванных рекурсивно копий функции "quick_sort" принимает в качестве параметра список, |
| 16 | + # содержащий 1 или 0 элементов, то мы выходим из этой копии функции "quick_sort" и возвращаем этот список |
| 17 | + # предыдущей копии функции "quick_sort" в стеке вызовов, поскольку если список содержит 1 или 0 элементов, |
| 18 | + # то он уже отсортирован по возрастанию. |
| 19 | + # Если изначально вызывается функция "quick_sort", которая принимает в качестве параметра список, |
| 20 | + # содержащий 1 или 0 элементов, то функция "quick_sort" сразу возвращает этот список, |
| 21 | + # поскольку если список содержит 1 или 0 элементов, то он уже отсортирован по возрастанию. |
| 22 | + # Функция "print()" выводит некую указанную информацию на экран или на какое-либо другое устройство вывода. |
| 23 | + # ---------- |
| 24 | + # Create the base case. |
| 25 | + # The base case in a recursive function is a part of the function code that describes |
| 26 | + # the condition for the termination of the function in order to prevent loops. |
| 27 | + # If one of the recursively called copies of the function "quick_sort" takes the list containing 1 or 0 elements |
| 28 | + # as a parameter, then we exit this recursively called copy of the function "quick_sort" |
| 29 | + # and it returns this list to the previous copy of the function "quick_sort" |
| 30 | + # in the call stack, since if a list contains 1 or 0 element, then this list is already sorted in ascending order. |
| 31 | + # If the function "quick_sort" is initially called with the list containing 1 or 0 elements as a parameter, |
| 32 | + # then the function "quick_sort" immediately returns this list, |
| 33 | + # since if a list contains 1 or 0 element, then this list is already sorted in ascending order. |
| 34 | + # The function "print()" prints the specified message to the screen, or other standard output device. |
| 35 | + if len(list_to_sort) < 2: |
| 36 | + return list_to_sort |
| 37 | + # Создаем рекурсивный случай. |
| 38 | + # Рекурсивный случай в рекурсивной функции - это часть кода функции, в которой функция вызывает сама себя |
| 39 | + # в целях выполнения какой-либо задачи. |
| 40 | + # Если список "list_to_sort" содержит 2 или больше элементов, то: |
| 41 | + # ---------- |
| 42 | + # Create the recursive case. |
| 43 | + # The recursive case in a recursive function is a part of the function code |
| 44 | + # in which the function calls itself in order to perform a task. |
| 45 | + # If the list "list_to_sort" contains 2 or more elements, then: |
| 46 | + else: |
| 47 | + # 1. Создается переменная "pivot", которая хранит опорный элемент списка "list_to_sort", |
| 48 | + # который равен элементу списка "list_to_sort" под индексом 0. |
| 49 | + # ---------- |
| 50 | + # 1. The variable "pivot", that stores the pivot element of the list "list_to_sort", |
| 51 | + # which is equal to the element of the list "list_to_sort" at index 0, is created. |
| 52 | + pivot = list_to_sort[0] |
| 53 | + # 2. Формируется подсписок элементов списка "list_to_sort", |
| 54 | + # которые меньше или равны опорному элементу списка "list_to_sort". |
| 55 | + # Для этого мы перебираем все элементы списка "list_to_sort", |
| 56 | + # кроме первого элемента этого списка, при помощи цикла for, |
| 57 | + # и сохраняем в подсписке "less" только те элементы, которые меньше или равны опорному элементу. |
| 58 | + # ---------- |
| 59 | + # 2. The sublist of the elements of the list "list_to_sort", |
| 60 | + # which are less than or equal to the pivot element of the list "list_to_sort", is formed. |
| 61 | + # To do this, we iterate over all the elements of the list "list_to_sort", |
| 62 | + # except for the first element of this list, using a for loop, and store in the sublist "less" |
| 63 | + # only those elements which are less than or equal to the pivot element. |
| 64 | + less = [i for i in list_to_sort[1:] if i <= pivot] |
| 65 | + # 3. Формируется подсписок элементов списка "list_to_sort", |
| 66 | + # которые больше опорного элемента списка "list_to_sort". |
| 67 | + # Для этого мы перебираем все элементы списка "list_to_sort", |
| 68 | + # кроме первого элемента этого списка, при помощи цикла for, |
| 69 | + # и сохраняем в подсписке "greater" только те элементы, которые больше опорного элемента. |
| 70 | + # ---------- |
| 71 | + # 3. The sublist of the elements of the list "list_to_sort", |
| 72 | + # which are greater than the pivot element of the list "list_to_sort", is formed. |
| 73 | + # To do this, we iterate over all the elements of the list "list_to_sort", |
| 74 | + # except for the first element of this list, using a for loop, |
| 75 | + # and store in the sublist "greater" only those elements which are greater than the pivot element. |
| 76 | + greater = [i for i in list_to_sort[1:] if i > pivot] |
| 77 | + # 4. Рекурсивно вызываются копии функции "quick_sort" для подсписков "less" и "greater", |
| 78 | + # при этом результаты работ этих рекурсивно вызванных копий функции "quick_sort" конкатенируются |
| 79 | + # с опорным элементом (["less" + "pivot" + "greater"]). |
| 80 | + # Когда рекурсивно вызывается копия функции "quick_sort", которая принимает в качестве параметра список, |
| 81 | + # содержащий 1 или 0 элементов, то срабатывает базовый случай. |
| 82 | + # Копии функции "quick_sort" в стеке вызовов поочередно завершают свою работу и |
| 83 | + # возвращают свои рассчитанные значения предыдущим рекурсивно вызванным копиям функции "quick_sort" до тех пор, |
| 84 | + # пока не завершит работу самая первая вызванная функция "quick_sort". |
| 85 | + # ---------- |
| 86 | + # 4. Copies of the function "quick_sort" are recursively called for the sublists "less" and "greater", |
| 87 | + # and the results of these recursively called copies of the function "quick_sort" |
| 88 | + # are concatenated to the pivot element (["less" + "pivot" + "greater"]). |
| 89 | + # When a copy of the function "quick_sort" is recursively called with the list containing 1 or 0 elements |
| 90 | + # as a parameter, then the base case is triggered. |
| 91 | + # The copies of the function "quick_sort" in the call stack terminate one by one and return |
| 92 | + # their calculated values to the previous recursively called copies of the function "quick_sort" |
| 93 | + # until the very first called function "quick_sort" stops its work. |
| 94 | + return quick_sort(less) + [pivot] + quick_sort(greater) |
| 95 | + |
| 96 | + |
| 97 | +# Пытаемся отсортировать список [2, 0, 6, 9, 7, 7] по возрастанию. |
| 98 | +# Функция "print()" выводит некую указанную информацию на экран или на какое-либо другое устройство вывода. |
| 99 | +# ---------- |
| 100 | +# Try to sort the list [2, 0, 6, 9, 7, 7] in ascending order. |
| 101 | +# The function "print()" prints the specified message to the screen, or other standard output device. |
| 102 | +print(quick_sort([2, 0, 6, 9, 7, 7])) |
0 commit comments