<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">"""
A module with just the functions for insertion sort.

You can run this by typing "python insertion_sort.py" on the command line.

Author: Walker M. White (wmw2), Anne Bracy (awb93), Daisy Fan (kdf4)
Date:   May 2021
"""

def swap(b, h, k):
    """
    Procedure swaps b[h] and b[k]

    Parameter b: The list to rearrange
    Precondition: b is a mutable sequence (e.g. a list).

    Parameter h: The first position to swap
    Precondition: h is an int and a valid position in b

    Parameter k: The second position to swap
    Precondition: k is an int and a valid position in b
    """
    temp = b[h]
    b[h] = b[k]
    b[k] = temp

def push_down(b, k):
    """
    Moves the value at position k into its sorted position in b[0..k-1].

    Parameter b: The list to rearrange
    Precondition: b is a list, with b[0..k-1] sorted

    Parameter k: The position to push down into b[0..k-1]
    Precondition: k is an int and a valid position in b
    """
    while k &gt; 0 and b[k-1] &gt; b[k]:
        swap(b, k-1, k)
        k= k-1

def insertion_sort(b):
    """
    Sorts the array b using the Insertion Sort algorithm (in n^2 time)

    Parameter b: The sequence to sort
    Precondition: b is a mutable sequence (e.g. a list).
    """
    # At start: length 1 segment b[0..0] is already sorted
    for i in range(1,len(b)):
        # move b[i] into its sorted position in b[0..i-1]
        push_down(b, i)

# Try it out
my_list = [2,4,6,2,6,9,8,2,3]
print("list before:")
print(my_list)
insertion_sort(my_list)
print("list after insertion-sorting:")
print(my_list)
</pre></body></html>