These questions follow Sorting. Use this list of lap times in seconds throughout, and do the first two questions on paper before touching a keyboard:

times = [64, 25, 12, 22, 11]

By hand

  1. Write out the list after each comparison of the first pass of a bubble sort. Where does the largest value end up, and why is that guaranteed?
  2. Write out the list after each pass of an insertion sort. Which pass does the most work, and why?
  3. Find the fault. This bubble sort crashes. Say exactly why, name the error, and give the two corrections it needs.
    def bubble_sort(values):
        for pass_number in range(len(values)):
            for position in range(len(values)):
                if values[position] > values[position + 1]:
                    values[position], values[position + 1] = (
                        values[position + 1], values[position])
        return values

In code

  1. Write insertion_sort(values). Test it on the lap times, on an empty list, and on a list of one item.
  2. Write selection_sort(values). Say what it does that insertion sort does not, and which of the two you would rather run on nearly-sorted data.
  3. Sort ["Rowan", "bea", "Ali", "nadia", "Sam"] with your insertion sort. Explain the result, then make it sort the way a person would expect.
  4. Sort a list of Volunteer objects (each with name and hours) by hours, fewest first, by changing exactly one line of your insertion sort.
  5. Stability. Sort [("Rowan", 2), ("Nadia", 1), ("Bea", 2), ("Ali", 1)] by the second value using > in the comparison, then again using >=. Report both results and say which one you would hand to a coach who reads ties as arrival order.
  6. Counting. Count the comparisons your insertion sort makes on sorted, shuffled, and reversed lists of 100, 200, and 400 items. What happens to each column when the size doubles?

Answers

Curriculum connection

A1.3

demonstrate the ability to use non-numeric comparisons (e.g., strings, comparable interface) in computer programs;

Link to original

A3.4

create a sort algorithm (e.g., bubble, insertion, selection) to sort data in an array;

Link to original

C2.1

demonstrate the ability to analyse a precondition (i.e., starting state) and a postcondition (i.e., ending state) in an algorithm;

Link to original

C2.3

compare the efficiency of sorting algorithms, using run times and computational complexity analysis (e.g., to analyse the number of statements executed, the number of iterations of a loop, or the number of comparisons performed);

Link to original