MCS 275 Spring 2022

David Dumas

Course bulletins:

- Project 2 due 6pm central Friday, February 25.
- Worksheet 7 will explore the maze solver / generator in more depth.

You will write functions (mostly recursive) to enumerate **integer splittings**.

E.g. `1+2+3`

and `3+1+2`

and `4+2`

are splittings of `6`

- Discuss the theory of
- Divide and conquer
- Sorting
- Mergesort
- Implement mergesort

A strategy that often involves recursion.

**Split**a problem into parts.**Solve**for each part.**Merge**the partial solutions into a solution of the original problem.

Not always possible or a good idea. It only works if merging partial solutions is easier than solving the entire problem.

Suppose you have a list of objects that can be compared with `==`

, `>`

, `<`

.

You'd like to reorder them in increasing order.

This problem is called **comparison sort**. There are many solutions.

A divide-and-conquer solution to comparison sort.

It is a fast solution, often used in practice.

Key: It is pretty easy to take two sorted lists and merge them into a single sorted list.

So, let's divide our list into halves, sort each one (recursively), then merge them.

Now we'll formalize this.

`mergesort`

:**Input:** list `L`

whose elements support comparison.

**Goal:** return a list that contains the items from `L`

but in sorted order.

- If
`L`

has 0 or 1 elements, return`L`

- Otherwise, divide
`L`

into rougly equal pieces`L0`

and`L1`

. - Use recursive calls to sort
`L0`

and`L1`

. - Use
`merge`

to merge these sorted lists and return the result.

This algorithm depends on having a function `merge`

that can merge two sorted lists into a single sorted list.

`merge`

:**Input:** sorted lists `L0`

and `L1`

.

**Goal:** return a sorted list with same items as `L0+L1`

- Make a new empty list
`L`

- Make integer variables
`i0,i1`

to keep track of current position in`L0,L1`

respectively. Set to zero. - While
`i0 < len(L0)`

and`i1 < len(L1)`

, do the following:- Check which of
`L0[i0]`

and`L1[i1]`

is smaller. - Append the smaller one to
`L`

. - Increment whichever one of
`i0,i1`

was used.

- Check which of
- Append any remaining portion of
`L0`

to`L`

. - Append any remaining portion of
`L1`

to`L`

.

Let's implement `mergesort`

in Python.

- Recursion references from Lecture 13.
- Making nice visualizations of sorting algorithms is a cottage industry in CS education. Some you might like to check out:
- 2D visualization through color sorting by Linus Lee
- Animated bar graph visualization of many sorting algorithms by Alex Macy
- Slanted line animated visualizations of mergesort and quicksort by Mike Bostock

- 2022-02-16 Initial publication