Two way partition the data into smaller and greater lists, in relationship to the pivot :param arr: The data to be searched (a list) :param target: The rank to be searched :return: element at rank target >>> quick_select([2, 4, 5, 7, 899, 54, 32], 5) 32 >>> quick_se
(arr: list, target: int)
| 59 | |
| 60 | |
| 61 | def quick_select(arr: list, target: int) -> int: |
| 62 | """ |
| 63 | Two way partition the data into smaller and greater lists, |
| 64 | in relationship to the pivot |
| 65 | :param arr: The data to be searched (a list) |
| 66 | :param target: The rank to be searched |
| 67 | :return: element at rank target |
| 68 | |
| 69 | >>> quick_select([2, 4, 5, 7, 899, 54, 32], 5) |
| 70 | 32 |
| 71 | >>> quick_select([2, 4, 5, 7, 899, 54, 32], 1) |
| 72 | 2 |
| 73 | >>> quick_select([5, 4, 3, 2], 2) |
| 74 | 3 |
| 75 | >>> quick_select([3, 5, 7, 10, 2, 12], 3) |
| 76 | 5 |
| 77 | """ |
| 78 | |
| 79 | # Invalid Input |
| 80 | if target > len(arr): |
| 81 | return -1 |
| 82 | |
| 83 | # x is the estimated pivot by median of medians algorithm |
| 84 | x = median_of_medians(arr) |
| 85 | left = [] |
| 86 | right = [] |
| 87 | check = False |
| 88 | for i in range(len(arr)): |
| 89 | if arr[i] < x: |
| 90 | left.append(arr[i]) |
| 91 | elif arr[i] > x: |
| 92 | right.append(arr[i]) |
| 93 | elif arr[i] == x and not check: |
| 94 | check = True |
| 95 | else: |
| 96 | right.append(arr[i]) |
| 97 | rank_x = len(left) + 1 |
| 98 | if rank_x == target: |
| 99 | answer = x |
| 100 | elif rank_x > target: |
| 101 | answer = quick_select(left, target) |
| 102 | elif rank_x < target: |
| 103 | answer = quick_select(right, target - rank_x) |
| 104 | return answer |
| 105 | |
| 106 | |
| 107 | print(median_of_five([5, 4, 3, 2])) |
nothing calls this directly
no test coverage detected