Created
November 23, 2009 22:17
-
-
Save mckoss/241429 to your computer and use it in GitHub Desktop.
Kth Largest Select in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def Select(a, i, first=0, last=None): | |
if last is None: | |
last = len(a)-1 | |
p = Pivot(a, first, last) | |
if p == i: | |
return a[p] | |
if p < i: | |
return Select(a, i, p+1, last) | |
return Select(a, i, first, p-1) | |
swap_count = 0 | |
def Pivot(a, first, last): | |
def Swap(i, j): | |
global swap_count | |
(a[i], a[j]) = (a[j], a[i]) | |
swap_count += 1 | |
i = (first+last)/2 | |
Swap(first, i) | |
v = a[first] | |
j = first+1 | |
for i in range(first+1, last+1): | |
if a[i] < v: | |
Swap(i, j) | |
j += 1 | |
Swap(first,j-1) | |
return j-1 | |
import random | |
size = 200 | |
a = [random.randrange(size) for i in range(size)] | |
s = list(a) | |
s.sort() | |
for i in range(size): | |
t = list(a) | |
swap_count = 0 | |
x = Select(t,i) | |
print "%d -> %d (%s) [%d swaps]" % (i, x, "Good" if x == s[i] else "FAIL", swap_count) | |
print s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment