Skip to content

Commit ab31f1a

Browse files
committed
Add median() function using Quickselect
1 parent fff34ed commit ab31f1a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Diff for: searches/quick_select.py

+31
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,34 @@ def quick_select(items: list, index: int):
6060
# must be in larger
6161
else:
6262
return quick_select(larger, index - (m + count))
63+
64+
65+
def median(data: list):
66+
"""One common application of Quickselect is finding the median, which is
67+
the middle element (or average of the two middle elements) in a dataset. It
68+
works efficiently on unsorted lists by partially sorting the data without
69+
fully sorting the entire list.
70+
71+
>>> import random
72+
>>> random.seed(0)
73+
74+
>>> d = [2, 2, 3, 9, 9]
75+
>>> random.shuffle(d)
76+
>>> d
77+
[3, 2, 2, 9, 9]
78+
>>> median(d)
79+
3
80+
81+
>>> d = [2, 2, 3, 9, 9, 9]
82+
>>> random.shuffle(d)
83+
>>> median(d)
84+
6.0
85+
86+
"""
87+
mid, rest = divmod(len(data), 2)
88+
if rest:
89+
return quick_select(data, mid)
90+
else:
91+
low_mid = quick_select(data, mid - 1)
92+
high_mid = quick_select(data, mid)
93+
return (low_mid + high_mid) / 2

0 commit comments

Comments
 (0)