TheAlgorithms-Python
97 строк · 2.9 Кб
1"""
2Python program for Bitonic Sort.
3
4Note that this program works only when size of input is a power of 2.
5"""
6
7from __future__ import annotations8
9
10def comp_and_swap(array: list[int], index1: int, index2: int, direction: int) -> None:11"""Compare the value at given index1 and index2 of the array and swap them as per12the given direction.
13
14The parameter direction indicates the sorting direction, ASCENDING(1) or
15DESCENDING(0); if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are
16interchanged.
17
18>>> arr = [12, 42, -21, 1]
19>>> comp_and_swap(arr, 1, 2, 1)
20>>> arr
21[12, -21, 42, 1]
22
23>>> comp_and_swap(arr, 1, 2, 0)
24>>> arr
25[12, 42, -21, 1]
26
27>>> comp_and_swap(arr, 0, 3, 1)
28>>> arr
29[1, 42, -21, 12]
30
31>>> comp_and_swap(arr, 0, 3, 0)
32>>> arr
33[12, 42, -21, 1]
34"""
35if (direction == 1 and array[index1] > array[index2]) or (36direction == 0 and array[index1] < array[index2]37):38array[index1], array[index2] = array[index2], array[index1]39
40
41def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> None:42"""43It recursively sorts a bitonic sequence in ascending order, if direction = 1, and in
44descending if direction = 0.
45The sequence to be sorted starts at index position low, the parameter length is the
46number of elements to be sorted.
47
48>>> arr = [12, 42, -21, 1]
49>>> bitonic_merge(arr, 0, 4, 1)
50>>> arr
51[-21, 1, 12, 42]
52
53>>> bitonic_merge(arr, 0, 4, 0)
54>>> arr
55[42, 12, 1, -21]
56"""
57if length > 1:58middle = int(length / 2)59for i in range(low, low + middle):60comp_and_swap(array, i, i + middle, direction)61bitonic_merge(array, low, middle, direction)62bitonic_merge(array, low + middle, middle, direction)63
64
65def bitonic_sort(array: list[int], low: int, length: int, direction: int) -> None:66"""67This function first produces a bitonic sequence by recursively sorting its two
68halves in opposite sorting orders, and then calls bitonic_merge to make them in the
69same order.
70
71>>> arr = [12, 34, 92, -23, 0, -121, -167, 145]
72>>> bitonic_sort(arr, 0, 8, 1)
73>>> arr
74[-167, -121, -23, 0, 12, 34, 92, 145]
75
76>>> bitonic_sort(arr, 0, 8, 0)
77>>> arr
78[145, 92, 34, 12, 0, -23, -121, -167]
79"""
80if length > 1:81middle = int(length / 2)82bitonic_sort(array, low, middle, 1)83bitonic_sort(array, low + middle, middle, 0)84bitonic_merge(array, low, length, direction)85
86
87if __name__ == "__main__":88user_input = input("Enter numbers separated by a comma:\n").strip()89unsorted = [int(item.strip()) for item in user_input.split(",")]90
91bitonic_sort(unsorted, 0, len(unsorted), 1)92print("\nSorted array in ascending order is: ", end="")93print(*unsorted, sep=", ")94
95bitonic_merge(unsorted, 0, len(unsorted), 0)96print("Sorted array in descending order is: ", end="")97print(*unsorted, sep=", ")98