Tags: best and worst case, lecture-06, mergesort
True or False: the best case time complexity of mergesort is \(\Theta(n)\).
False.
Mergesort doesn't stop early: it always splits the array in half all the way down and merges everything back together, no matter what the input is (even if it is already sorted). Each of the \(\Theta(\log n)\) levels of recursion does \(\Theta(n)\) merging work, so the best case is \(\Theta(n \log n)\), the same as the worst case.
Tags: lecture-06, mergesort
Suppose mergesort is called on an array of size \(n\). In total, how many calls to merge are made over all calls to mergesort?
\(\Theta(n)\).
Each call to mergesort on an array of size 2 or more splits it in two, makes two recursive calls, and then calls merge exactly once. Calls on arrays of size 1 (or 0) are base cases: they don't recurse and don't merge. So the number of calls to merge is the number of non-base-case calls, i.e., the number of internal nodes of the recursion tree.
The recursion tree has one leaf for each element of the array, so it has \(n\) leaves. Every internal node has exactly two children, and a tree like that with \(n\) leaves has \(n - 1\) internal nodes. (Each merge combines two sorted pieces into one, starting from \(n\) pieces of size 1 and ending with one piece, so it takes \(n - 1\) merges.) For example, when \(n = 8\) there are \(4 + 2 + 1 = 7\) merges. So the total is \(n - 1 = \Theta(n)\).
Tags: lecture-06, mergesort, recursion
Consider the code for mergesort and merge where a new print-statement has been added to merge:
def mergesort(arr):
"""Sort array in-place."""
if len(arr) > 1:
middle = math.floor(len(arr) / 2)
left = arr[:middle]
right = arr[middle:]
mergesort(left)
mergesort(right)
merge(left, right, arr)
def merge(left, right, out):
"""Merge sorted arrays, store in out."""
left.append(float('inf'))
right.append(float('inf'))
left_ix = 0
right_ix = 0
for ix in range(len(out)):
print("Here!") # <---- the newly-added line
if left[left_ix] < right[right_ix]:
out[ix] = left[left_ix]
left_ix += 1
else:
out[ix] = right[right_ix]
right_ix += 1
Suppose mergesort is called on an array of size \(n\). In total, how many times will "Here!" be printed?
\(\Theta(n \log n)\).
The print is inside merge's loop, which runs once for each element of out. So a call to merge that produces an array of size \(m\) prints “Here!” \(m\) times, i.e., the number of prints is exactly the number of elements merged.
Now look at the recursion tree of mergesort. At each level, the subarrays being sorted together make up the whole array (each element is in exactly one of them), so the merges at that level produce at most \(n\) elements in total, and exactly \(n\) at every level above the leaves. There are \(\Theta(\log n)\) levels, since the size halves at each one. So the total number of prints is \(\Theta(n)\) per level times \(\Theta(\log n)\) levels, which is \(\Theta(n \log n)\). This is the same argument that shows mergesort takes \(\Theta(n \log n)\) time.
Tags: lecture-06, mergesort, recurrence relations
Consider the modification of mergesort shown below, where one of the recursive calls has been replaced by an in-place version of selection_sort. Recall that selection_sort takes \(\Theta(n^2)\) time.
def kinda_mergesort(arr):
"""Sort array in-place."""
if len(arr) > 1:
middle = math.floor(len(arr) / 2)
left = arr[:middle]
right = arr[middle:]
mergesort(left)
selection_sort(right)
merge(left, right, arr)
What is the time complexity of kinda_mergesort?
\(\Theta(n^2)\).
The function isn't actually recursive: it calls the regular mergesort on the left half, taking \(\Theta(n \log n)\) time, selection_sort on the right half, taking \(\Theta((n/2)^2) = \Theta(n^2)\) time, and merge, taking \(\Theta(n)\) time. The selection sort dominates, so the total is \(\Theta(n^2)\).
Tags: best and worst case, lecture-06, mergesort
Suppose arr is a list-of-lists with \(n\) inner lists, each containing \(n\) numbers. What is the best case time complexity of the following function?
import math
def average_median(arr):
"""Compute the mean of the row medians."""
msum = 0
for row in arr:
mergesort(row) # sort the row using the mergesort algorithm
msum += row[math.floor(len(row) / 2)]
return msum / len(arr)
\(\Theta(n^2 \log n)\).
Mergesort takes \(\Theta(k \log k)\) time on an array of size \(k\) in every case, including the best case. The loop sorts \(n\) rows of size \(n\), taking \(\Theta(n \log n)\) time for each, and the rest of the loop body takes constant time. So the best case is \(\Theta(n^2 \log n)\).
Tags: best and worst case, lecture-06, mergesort
Your friend has written a modified version of mergesort that they claim has an improved best-case time complexity:
def better_mergesort(arr):
if is_already_sorted(arr):
return
else:
mergesort(arr)
Here, is_already_sorted is a function that takes in an array and returns True if and only if the array is in sorted order. Assume that is_already_sorted is implemented efficiently (meaning, it has the best possible time complexity). What is the best case time complexity of better_mergesort?
\(\Theta(n)\).
The best case is when arr is already sorted, so that only is_already_sorted runs. Checking whether an array is sorted requires looking at every element, and can be done in \(\Theta(n)\) time by comparing each pair of adjacent elements. So the best case time complexity is \(\Theta(n)\).
Tags: lecture-06, mergesort
Below is the merge function from the mergesort algorithm, with an added print statement:
def merge(left, right, out):
"""Merge sorted arrays, store in out."""
print(len(left))
print(len(right))
left.append(float('inf'))
right.append(float('inf'))
left_ix = 0
right_ix = 0
for ix in range(len(out)):
if left[left_ix] < right[right_ix]:
out[ix] = left[left_ix]
left_ix += 1
else:
out[ix] = right[right_ix]
right_ix += 1
Suppose this version of merge is used in mergesort, and mergesort is called on the following list:
[6, 2, 7, 1, 9, 3, 8, 5]
If all of the numbers that are printed are added up, what will the sum be?
24.
Each call to merge prints the sizes of its two halves, which add up to the size of the subarray being merged. So we need the total size of all the subarrays that get merged. Since the list has 8 elements, the recursion splits it in halves evenly:
Arrays of size 1 are base cases and aren't merged. Each level's printed sizes add up to 8, the size of the whole list, and there are \(\log_2 8 = 3\) levels of merges, so the sum is \(3 \cdot 8 = 24\). Notice that the values in the list don't matter, only its length.
No 🌶️ problems in this topic.