Skip to content

Add median() function using Quickselect #12676

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions searches/quick_select.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,34 @@ def quick_select(items: list, index: int):
# must be in larger
else:
return quick_select(larger, index - (m + count))


def median(data: list):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is an application of the quick_select algorithm, can you move it to its own file?

"""One common application of Quickselect is finding the median, which is
the middle element (or average of the two middle elements) in a dataset. It
works efficiently on unsorted lists by partially sorting the data without
fully sorting the entire list.

>>> import random
>>> random.seed(0)

>>> d = [2, 2, 3, 9, 9]
>>> random.shuffle(d)
>>> d
[3, 2, 2, 9, 9]
>>> median(d)
3

>>> d = [2, 2, 3, 9, 9, 9]
>>> random.shuffle(d)
>>> median(d)
6.0

"""
mid, rest = divmod(len(data), 2)
if rest:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rename to remainder?

return quick_select(data, mid)
else:
low_mid = quick_select(data, mid - 1)
high_mid = quick_select(data, mid)
return (low_mid + high_mid) / 2

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: add comments.
Especially on the else block.