1 Sep 2009 06:06
A faster median (Wirth's method)
Sturla Molden <sturla <at> molden.no>
2009-09-01 04:06:50 GMT
2009-09-01 04:06:50 GMT
We recently has a discussion regarding an optimization of NumPy's median
to average O(n) complexity. After some searching, I found out there is a
selection algorithm competitive in speed with Hoare's quick select. It
has the advantage of being a lot simpler to implement. In plain Python:
import numpy as np
def wirthselect(array, k):
""" Niklaus Wirth's selection algortithm """
a = np.ascontiguousarray(array)
if (a is array): a = a.copy()
l = 0
m = a.shape[0] - 1
while l < m:
x = a[k]
i = l
j = m
while 1:
while a[i] < x: i += 1
while x < a[j]: j -= 1
if i <= j:
tmp = a[i]
a[i] = a[j]
a[j] = tmp
i += 1
j -= 1
(Continue reading)
RSS Feed