Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Sort a stack using recursion

"""
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 :: how to select a single cell in a pandas dataframe 
Python :: how to save a python object in a file 
Python :: clamp number in python 
Python :: csv module remove header title python 
Python :: add row in db django 
Python :: commentaire python 
Python :: tqdm progress bar python 
Python :: pandas get day names 
Python :: python check for duplicate 
Python :: two for loops in list comprehension 
Python :: file base name and extension python 
Python :: python replace character in string 
Python :: is there a way to skip the first loop on a for loop python 
Python :: formatting in python 
Python :: find substr within a str in python 
Python :: how to sort a dictionary py 
Python :: color name to hex python 
Python :: python 2 deprecated 
Python :: copy string python 
Python :: alphabet python 
Python :: create limit using matplotlib 
Python :: make the program title a name python 
Python :: pandas describe kurtosis skewness 
Python :: Export a Pandas dataframe as a table image 
Python :: pandas select a row 
Python :: urllib.request.urlretrieve 
Python :: appending to a file in python 
Python :: python package version in cmd 
Python :: lambda condition python 
Python :: jpython 
ADD CONTENT
Topic
Content
Source link
Name
9+3 =