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

Function partition

data_structures/arrays/kth_largest_element.py:8–41  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

6
7
8def 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
44def kth_largest_element(arr: list[int], position: int) -> int:

Callers 1

kth_largest_elementFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected