Implementing algorithms, while loops
Insertion sort in Python
Recall the insertion sort algorithm:
index = 1 while index < length of list: insertion-index = index while list[insertion-index] < list[insertion-index - 1]: swap list[insertion-index] and list[insertion-index - 1] insertion-index = insertion-index - 1 index = index - 1
Now that we have a pretty good idea of what insertion sort looks like as an algorithm, can we write a Python program that implements it? We can start off like this:
def insertion_sort(l: list): """sorts the input list using the insertion sort algorithm""" pass
What should this function return? It’s just modifying the list in place, so it doesn’t need to return anything.
How should we implement “while”? We could try a for-loop:
def insertion_sort(l: list): """sorts the input list using the insertion sort algorithm""" for element in l: pass
This isn’t going to work–a for
-loop gives us a name for each element in a
list, but we need each index in the list! There are a couple of ways to do
this in Python. For now, we’ll opt for the most direct translation of the
pseudocode, which uses a while
-loop.
While loops
A while
-loop is sort of like a repeated “if”. They look like this:
while CONDITION:
BODY
This will execute BODY
over and over again, as long as CONDITION
is true.
While loops are pretty powerful–anything we can do with for
-loops, we can do
with while
-loops. So for instance, how would we write a function like this
using while
?
def print_in_list(l: list): for item in l: print(item)
We will need to look at every element of the list, in order, and print it out. How can we get one element of the list?
We could write something like this:
def print_in_list(l: list): index = 0 while index < len(l): print(l[item]) index = index + 1
What happens if we don’t include the last line? The function will execute forever, printing the first item of the list over and over again!
Back to insertion sort
def insertion_sort(l: list): """sorts the input list using the insertion sort algorithm""" index = 1 while index < len(l): pass
A while
loop executes its body over and over again, as long as the condition
is true. You can think of it like a repeated if
. while
loops are very
powerful, but it’s also easy to mess up–what will happen if we execute this
function right now? (It will spin forever).
See the lecture capture for the details of how we completed this function. Here’s what we ended up with:
def insertion_sort(l: list): """sorts the input list using the insertion sort algorithm""" index = 1 while index < len(l): insertion_index = index while insertion_index > 0 and l[insertion_index] < l[insertion_index - 1]: # swap the two elements element = l[insertion_index] l[insertion_index] = l[insertion_index - 1] l[insertion_index - 1] = element insertion_index = insertion_index - 1 index = index + 1