Advertisement
Guest User

Stack sort

a guest
Oct 18th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.73 KB | None | 0 0
  1. def sort(stack):
  2.   if len(stack) == 1:
  3.     return stack
  4.   mid = len(stack)//2
  5.   oStack = []
  6.   for i in range(mid): # move top half to other stack
  7.     oStack.append(stack.pop())
  8.   sort(oStack)
  9.   sort(stack)
  10.  
  11.   fStack = [] # Merge into final stack
  12.   while len(stack) > 0 and len(oStack) > 0:
  13.     if stack[-1] < oStack[-1]:
  14.       fStack.append(stack.pop())
  15.     else:
  16.       fStack.append(oStack.pop())
  17.      
  18.   while len(stack) > 0:
  19.     fStack.append(stack.pop())
  20.    
  21.   while len(oStack) > 0:
  22.     fStack.append(oStack.pop())
  23.    
  24.   while len(fStack) > 0: # Move everything from final stack to stack as it is in reverse on final stack
  25.     stack.append(fStack.pop())
  26.   return stack
  27.  
  28. print(sort([1,2,5,1,3,7,8,1,2,10,12,7]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement