Skip to content

Instantly share code, notes, and snippets.

@tomachalek
Last active January 27, 2016 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomachalek/5547d9108e788d60fcdf to your computer and use it in GitHub Desktop.
Save tomachalek/5547d9108e788d60fcdf to your computer and use it in GitHub Desktop.
An implementation of the 'QuickSelect' algorithm (a.k.a. Hoare's selection algorithm)
def partition(data, left, right, pivot_idx):
pivot_value = data[pivot_idx]
real_pivot_idx = left
data[pivot_idx], data[right] = data[right], data[pivot_idx]
for i in range(left, right + 1):
if data[i] < pivot_value:
data[i], data[real_pivot_idx] = data[real_pivot_idx], data[i]
real_pivot_idx += 1
data[right], data[real_pivot_idx] = data[real_pivot_idx], data[right]
return real_pivot_idx
def quickselect(data, n):
left = 0
right = len(data) - 1
while True:
if left == right:
return data[left]
pivot_idx = (left + right) / 2
pivot_idx = partition(data, left, right, pivot_idx)
if n == pivot_idx:
return data[n]
elif n < pivot_idx:
right = pivot_idx - 1
else:
left = pivot_idx + 1
def median(data):
m = quickselect(data, len(data) / 2)
if len(data) % 2 == 0:
m2 = quickselect(data, len(data) / 2 - 1)
return (m2 + m) / 2.0
else:
return m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment