Skip to content

Instantly share code, notes, and snippets.

@gustavoatt
Created July 31, 2012 15:30
Show Gist options
  • Save gustavoatt/3217842 to your computer and use it in GitHub Desktop.
Save gustavoatt/3217842 to your computer and use it in GitHub Desktop.
Sort of a stack with two stacks using insertion sort
#!/usr/bin/env python
from collections import deque
# Sort using insertion sort with stacks O(n^2)
def sort_stack(l):
res_stack = deque()
# We keep res_stack always sorted
while len(l) > 0:
current = l.pop()
while True:
if len(res_stack) == 0:
res_stack.append(current)
break
elem = res_stack.pop()
if elem <= current:
res_stack.append(elem)
res_stack.append(current)
break
else:
l.append(elem)
return res_stack
print sort_stack(deque([1, 5, -1, 6, 0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment