Created
July 31, 2012 15:30
-
-
Save gustavoatt/3217842 to your computer and use it in GitHub Desktop.
Sort of a stack with two stacks using insertion sort
This file contains 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
#!/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