Skip to content

Instantly share code, notes, and snippets.

@damzam
Created February 15, 2013 07:15
Show Gist options
  • Save damzam/4958949 to your computer and use it in GitHub Desktop.
Save damzam/4958949 to your computer and use it in GitHub Desktop.
def sort_nuts_and_bolts(nuts, bolts):
"""Sort nuts and bolts in O(N log N) time"""
def sort(nuts, bolts):
if len(nuts) == 0:
return []
lnuts, rnuts, lbolts, rbolts = [], [], [], []
nut = nuts.pop()
bolt = None
for b in bolts:
if b == nut and not bolt:
bolt = b
pair = [(nut, b)]
elif b <= nut:
lbolts.append(b)
else:
rbolts.append(b)
for n in nuts:
if n <= bolt:
lnuts.append(n)
else:
rnuts.append(n)
return sort(lnuts, lbolts) + pair + sort(rnuts, rbolts)
return zip(*sort(nuts, bolts))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment