Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

How to recursively sort the elements of a stack, in Python?

"""
This implementation demonstrates how 
to recursively sort a stack in place.

Let n be the size of the stack.

Time complexity: O(n^2)
Space complexity: O(n)
"""
def sort_stack(stack):
    # base case
    if len(stack) == 0:
        return
    top_element = stack.pop()
    # Pop elements from stack
    sort_stack(stack)
    # Insert them in order into stack
    insert_in_order(stack, top_element)

def insert_in_order(stack, value):
    # Insert value at right position within stack
    if len(stack) == 0 or stack[len(stack)-1] <= value:
        stack.append(value)
        return

    top = stack.pop()
    # Same process all over again but one less element
    insert_in_order(stack, value)

    stack.append(top)
    
stack = [1, 4, 2, 3]
sort_stack(stack)
print("After sorting:", stack)  # After sorting: [1, 2, 3, 4]
Comment

PREVIOUS NEXT
Code Example
Python :: set seed train test split 
Python :: install python 3.7 centos 
Python :: skip error python 
Python :: python - remove columns with same name and keep first 
Python :: one-line for loop python 
Python :: pandas count rows in column 
Python :: python progress bar 
Python :: how to create string in python 
Python :: extend a list python 
Python :: else if in django template 
Python :: get just filename without extension from the path python 
Python :: smtplib send pdf 
Python :: numpy arrauy to df 
Python :: dataframe move row up one 
Python :: numpy euclidean distance 
Python :: how to press enter in selenium python 
Python :: decimal in python 
Python :: python 2 is no longer supported 
Python :: make a nested list flat python 
Python :: python how to keep turtle window open 
Python :: django models integer field default value 
Python :: print last exceuted query python 
Python :: fnd closest element in array numpy 
Python :: magic methods python 
Python :: python remove key from dict 
Python :: replace multiple values in pandas column 
Python :: print even numbers in python 
Python :: pandas for column in dataframe 
Python :: python iterate set 
Python :: pattern program in python 
ADD CONTENT
Topic
Content
Source link
Name
9+4 =