Back

Developing an understanding of our insertion sort program

It can be quite difficult understanding what is happening in any program, but sorting algorithms can be especially difficult to understand. There are a few techniques we can use to help us. One thing we can usefully do is to print out the list after putting each element in its correct place.

We will modify the print statements so that it becomes a function. To use the function, all we have to do is say its name (printArray) and tell it what array to use (myArray). One thing to remember about functions - you should always write them before you use them! The code for the function must go above any code that calls them.

Q1. Modify your previous program code to get this working.

python4 

Q2. Try sorting 5 numbers, 10 numbers and 20 numbers a few times. See how each element gets put in the correct place.
Q3.
 Find out using the Internet how to 'Comment out' this code so, rather than delete it, you just disable it for a while:

import random

#This code creates a list of random numbers.
myArray = [] # create an empty list
size = int(input('How many data items? >>> ')) # ask for the size required
for i in range(size): # for i= 0 to (size-1)
     myArray.append(random.randint(1,500)) # get a random number and append it

Q4. After you have commented out the above code, create a list of animals like this at the top of your program:

myArray=["adder", "zebra", "lion", "rat", "koala bear", "monkey", "shark", "ant"]

Run the program and check it works. Try and follow what happens to the list after each insertion by examining the printout of the list after each round.
Q5. Create a new list of friends, football teams, countries or whatever you like and sort them.
Q6. Look up the word 'array'. What does it mean? 

Back