Skip to content

Create quick_select.py #153

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

Merged
merged 1 commit into from
Oct 10, 2017
Merged
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
47 changes: 47 additions & 0 deletions searches/quick_select.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import collections
import sys
import random
import time
import math
"""
A python implementation of the quick select algorithm, which is efficient for calculating the value that would appear in the index of a list if it would be sorted, even if it is not already sorted
https://en.wikipedia.org/wiki/Quickselect
"""
def _partition(data, pivot):
"""
Three way partition the data into smaller, equal and greater lists,
in relationship to the pivot
:param data: The data to be sorted (a list)
:param pivot: The value to partition the data on
:return: Three list: smaller, equal and greater
"""
less, equal, greater = [], [], []
for element in data:
if element.address < pivot.address:
less.append(element)
elif element.address > pivot.address:
greater.append(element)
else:
equal.append(element)
return less, equal, greater

def quickSelect(list, k):
#k = len(list) // 2 when trying to find the median (index that value would be when list is sorted)
smaller = []
larger = []
pivot = random.randint(0, len(list) - 1)
pivot = list[pivot]
count = 0
smaller, equal, larger =_partition(list, pivot)
count = len(equal)
m = len(smaller)

#k is the pivot
if m <= k < m + count:
return pivot
# must be in smaller
elif m > k:
return quickSelect(smaller, k)
#must be in larger
else:
return quickSelect(larger, k - (m + count))