Question: The Python function mergesort recursively sorts a list of numbers U using a recursive divide-and-conquer algorithm, then returns a sorted list S. The function head

The Python function mergesort recursively 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 06–07 detect if U is trivially sorted. Lines 09–16 split U into two halves, L and R, of approximately equal lengths. Lines 17–18 recursively sort L and R. Lines 19–28 merge the sorted L and R back into a sorted list S.


01 def head (Q): 02 return QI0] 03 def tail(Q): 04 return Q[1:] 05 def mergesort (U): 06 if U-= [ ] or tail (U)-[]: 07 08 els


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

  1. Find a loop invariant for the splitting loop

  2. Use loop invariant to prove the initialization part

  3. Use loop invariant to prove the maintenance part

  4. Use loop invariant to prove the termination part

  5. Find the worst case run time of mergesort’s merging loop(lines 19-28). Do not find the run time for the rest of mergesort. Your answer must define T(n) where n is the number of elements to be sorted.

 

01 def head(Q): 02 return Q[0] 03 def tail(Q): 04 return Q[1:] 05 def mergesort (U): if U =- [] or tail (U) 06 =- (): 07 return U 08 else: 09 L = [) 10 R = while U !- U and tai1(U) != []: L = L + [head (U)] U - tail(U) R = R + [head (U)] U = tail(U) 11 12 13 14 15 16 L = L + U L = mergesort (L) R = mergesort (R) 17 18 19 S = [) while L I- [] and R != []: if head(L)

Step by Step Solution

3.44 Rating (147 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

solution Here we will find running time from line 1928 Line 19 does one assignment which takes one ... View full answer

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 Programming Questions!