Session 1
In this session we will focus on practical problems, where some are given as worked examples and others at practice problems. It is important that you study the worked examples on video prior to class. The problems are paired, so that a worked example is followed by a very similar practice problem. We will discuss the solution of the practice problems in class, but please think through how you want to solve the problem in advance.
Related reading: Stein et al. p. 31–36 or Rosen p. 375–382
1.1 Algorithms
Problem 1.2 (Stein et al 1.1 Problem 1) The following code sorts an array using the algorithm known as insertion sort:
What is the maximum number of times you may have to swap elements (Line 4)? Show how you arrive at the answer.
Problem 1.3 In Problems 1.1 and 1.2 the number of swaps may vary between lists. It is useful to describe the worst case, i.e. the lists which require the largest number of swaps.
- What is the worst case for selection sort?
- What is the worst case for insertion sort?
1.2 Electing people
Problem 1.5 A club of 12 people will elect two members for a steering committee. How many different choices do they have for two people out of 12?
Problem 1.7 A club of 12 people will elect a president and a treasurer. How many different choices do they have for these two roles when the same person cannot hold both posts?
1.3 More algorithms
Problem 1.9 The following code sorts an array using the algorithm known as bubble sort:
2 n = length(A)
3 for j = 1 to n−1 inclusive do
4 for i = 1 to n−1 inclusive do
5 /∗ if this pair is out of order ∗/
6 if A[i−1] > A[i] then
7 swap( A[i−1], A[i] )
8 end if
9 end for
10 end for
11 end procedure
What is the maximum number of times you may have to swap elements (Line 7)? Show how you arrive at the answer.
1.4 PINs and passwords
Problem 1.11 Imagine a computer system which uses passwords composed of exactly three Latin letters (case insensitive a to z). How many different passwords exist?
1.5 Some theory
In the examples and exercises we have used only one or two techniques over and over again. To be able to identify these techniques, and apply them quickly and correctly to new problems, we need some mathematical theory.
This video casts the counting problem in terms of set theory, and introduce partitioning and the sum principle.
Using the sum principle, it sometimes happen that all the partitions have the same size. Then the sum principle turns into a product principle. Additionally, the product principle also cover a range of special cases which are easily solved when you know how.
When partitioning a set, there are certain pitfalls to avoid. In particular, if the partitions are not disjoint, you end up double-counting. Watch the video to learn more.
1.6 Sports tournaments
Problem 1.12 Five mates want to arrange a private tournament of table tennis. Each participant should play each of the others exactly once. How many matches are required?