MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / comp_and_swap

Function comp_and_swap

sorts/bitonic_sort.py:10–38  ·  view source on GitHub ↗

Compare the value at given index1 and index2 of the array and swap them as per the given direction. The parameter direction indicates the sorting direction, ASCENDING(1) or DESCENDING(0); if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are interchanged. >>> arr =

(array: list[int], index1: int, index2: int, direction: int)

Source from the content-addressed store, hash-verified

8
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 per
12 the given direction.
13
14 The parameter direction indicates the sorting direction, ASCENDING(1) or
15 DESCENDING(0); if (a[i] > a[j]) agrees with the direction, then a[i] and a[j] are
16 interchanged.
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 """
35 if (direction == 1 and array[index1] > array[index2]) or (
36 direction == 0 and array[index1] < array[index2]
37 ):
38 array[index1], array[index2] = array[index2], array[index1]
39
40
41def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> None:

Callers 1

bitonic_mergeFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected