Skip to content

Commit 26ad689

Browse files
Add median() function using Quickselect (#12676)
* Add median() function using Quickselect * Update quick_select.py * Update quick_select.py * Update quick_select.py --------- Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
1 parent a2fa32c commit 26ad689

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

searches/quick_select.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,3 +60,25 @@ 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(items: list):
66+
"""
67+
One common application of Quickselect is finding the median, which is
68+
the middle element (or average of the two middle elements) in a sorted dataset.
69+
It works efficiently on unsorted lists by partially sorting the data without
70+
fully sorting the entire list.
71+
72+
>>> median([3, 2, 2, 9, 9])
73+
3
74+
75+
>>> median([2, 2, 9, 9, 9, 3])
76+
6.0
77+
"""
78+
mid, rem = divmod(len(items), 2)
79+
if rem != 0:
80+
return quick_select(items=items, index=mid)
81+
else:
82+
low_mid = quick_select(items=items, index=mid - 1)
83+
high_mid = quick_select(items=items, index=mid)
84+
return (low_mid + high_mid) / 2

0 commit comments

Comments
 (0)