doctype html> Lec 12: Mergesort

Lecture 12

Divide and Conquer

Mergesort

MCS 275 Spring 2024
Emily Dumas

View as:   Presentation   ·   PDF-exportable  ·   Printable

Lecture 12: Mergesort

Reminders and announcements:

  • Project 1 due 11:59pm Friday
  • Project 1 autograder is open
    • Please tell me if you have any trouble interpreting the report or if you think it is wrong.
  • Worksheet 5 posted; lab 5 should allow time to ask TA project questions

Divide and conquer

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.

Decrease and conquer

Divide and conquer

Comparison sort

Problem: A list of length n is given. For any two elements you are allowed to ask which one is "smaller". Using this information, put the list in increasing order.

Mergesort

A divide-and-conquer solution to comparison sort.

Fast, often used in practice.

Key: Two sorted lists can be easily merged into one sorted list.

Algorithm mergesort:

Input: list L whose elements support comparison.

Goal: return a list that contains the items from L but in sorted order.

  1. If L has 0 or 1 elements, return L
  2. Otherwise, divide L into rougly equal pieces L0 and L1.
  3. Recursively call mergesort on L0 and L1.
  4. Use merge to merge these sorted lists and return the result.

Mergesort example

But how to merge?

This algorithm depends on having a function merge that can merge two sorted lists into a single sorted list.

Algorithm merge:

Input: sorted lists L0 and L1.

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

  1. Make a new empty list L
  2. Make integer variables i0,i1 to keep track of current position in L0,L1 respectively. Set to zero.
  3. 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.
  4. Append any remaining portion of L0 to L.
  5. Append any remaining portion of L1 to L.

Merging sorted lists

Coding time

Let's implement mergesort in Python.

References