Question: The sorting algorithm Mergesort is shown below in Python. It sorts a list of numbers U using a recursive divide-and-conquer algorithm, then returns a sorted

The sorting algorithm Mergesort is shown below in Python. It sorts a list of numbers U using a recursive divide-and-conquer algorithm, then returns a sorted list S. The function head returns the first element of a nonempty list Q, and the function tail returns all but the first element of a nonempty list Q. Lines 0607 detect if U is trivially sorted. Lines 0916 split U into two halves, L and R, of approximately equal lengths. Lines 1718 recursively sort L and R. Lines 1928 merge the sorted L and R back into a sorted list S.

01 def head(Q): 02 return Q[0] 03 def tail(Q): 04 return Q[1:] 05 def mergesort(U): 06 if U == [] or tail(U) == []: 07 return U 08 else: 09 L = [] 10 R = [] 11 while U != [] and tail(U) != []: 12 L = L + [head(U)] 13 U = tail(U) 14 R = R + [head(U)] 15 U = tail(U) 16 L = L + U 17 L = mergesort(L) 18 R = mergesort(R) 19 S = [] 20 while L != [] and R != []: 21 if head(L) <= head(R): 22 S = S + [head(L)] 23 L = tail(L) 24 else: 25 S = S + [head(R)] 26 R = tail(R) 27 S = S + L + R 28 return S

Here are some examples of how head, tail and mergesort work, where the arrow means returns.

head([3])

3

tail([3])

head([2, 0, 1])

2

tail([2, 0, 1])

[0, 1]

mergesort([])

[]

mergesort([1])

[1]

mergesort([1, 0])

[0, 1]

mergesort([4, 3, 2, 1, 0])

[0, 1, 2, 3, 4]

1. Prove that mergesorts splitting loop is correct (lines 0916). Do not prove that the rest of mergesort is correct. You must use a loop invariant. Your proof must have three parts: initialization, maintenance, and termination.

1a.

Find a loop invariant for the splitting loop.

1b.

Use your loop invariant to prove the initialization part.

1c.

Use your loop invariant to prove the maintenance part.

1d.

Use your loop invariant to prove the termination part.

2. Find the worst case run time of mergesorts merging loop (lines 1928). Do not find the run time for the rest of mergesort. Do not use O, , or . Your answer must define T(n) where n is the number of elements to to be sorted. Asume that the run times of lines 19, 20 ..., 28 are constants c, c ..., c, respectively. All these constants are greater than 0, and some of them may be equal. Also assume that head, tail, and list concatenation all work in constant time.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!