Skip to content

Instantly share code, notes, and snippets.

@mckoss
Created November 23, 2009 22:17
Show Gist options
  • Save mckoss/241429 to your computer and use it in GitHub Desktop.
Save mckoss/241429 to your computer and use it in GitHub Desktop.
Kth Largest Select in Python
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