Partitions list based on the pivot element. This function rearranges the elements in the input list 'elements' such that all elements greater than or equal to the chosen pivot are on the right side of the pivot, and all elements smaller than the pivot are on the left side. Arg
(arr: list[int], low: int, high: int)
| 6 | |
| 7 | |
| 8 | def partition(arr: list[int], low: int, high: int) -> int: |
| 9 | """ |
| 10 | Partitions list based on the pivot element. |
| 11 | |
| 12 | This function rearranges the elements in the input list 'elements' such that |
| 13 | all elements greater than or equal to the chosen pivot are on the right side |
| 14 | of the pivot, and all elements smaller than the pivot are on the left side. |
| 15 | |
| 16 | Args: |
| 17 | arr: The list to be partitioned |
| 18 | low: The lower index of the list |
| 19 | high: The higher index of the list |
| 20 | |
| 21 | Returns: |
| 22 | int: The index of pivot element after partitioning |
| 23 | |
| 24 | Examples: |
| 25 | >>> partition([3, 1, 4, 5, 9, 2, 6, 5, 3, 5], 0, 9) |
| 26 | 4 |
| 27 | >>> partition([7, 1, 4, 5, 9, 2, 6, 5, 8], 0, 8) |
| 28 | 1 |
| 29 | >>> partition(['apple', 'cherry', 'date', 'banana'], 0, 3) |
| 30 | 2 |
| 31 | >>> partition([3.1, 1.2, 5.6, 4.7], 0, 3) |
| 32 | 1 |
| 33 | """ |
| 34 | pivot = arr[high] |
| 35 | i = low - 1 |
| 36 | for j in range(low, high): |
| 37 | if arr[j] >= pivot: |
| 38 | i += 1 |
| 39 | arr[i], arr[j] = arr[j], arr[i] |
| 40 | arr[i + 1], arr[high] = arr[high], arr[i + 1] |
| 41 | return i + 1 |
| 42 | |
| 43 | |
| 44 | def kth_largest_element(arr: list[int], position: int) -> int: |
no outgoing calls
no test coverage detected