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)
| 8 | |
| 9 | |
| 10 | def 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 | |
| 41 | def bitonic_merge(array: list[int], low: int, length: int, direction: int) -> None: |