algorithm - using Python to represent merge-sort,how to avoid a IndexError -


i know it's not correct,and have found another method without infinite number ,but still want know if corrected usage of infinite number.

def mergesort(a):     if len(a) > 1:         mid = len(a) / 2         left = a[0:mid]         right = a[mid:]          mergesort(left)         mergesort(right)          w = float("inf")         left.append(w)         right.append(w)         i,j = 0,0         k in range(len(a)):             if left[i] <= right[j]:                 a[k] = left[i]                 += 1             else:                 a[k] = right[j]                 j += 1   

the problem within for k in range(len(a)): loop; happens when have exhausted values in left there values remaining in right (or vice-versa)?

the linked method adds test looks like

if (left still has values) , ((right has no values) or (next_left < next_right)):     take value left 

your code above instead adds guard value, ensuring if on left guard value guaranteed greater non-guard right value (and vice-versa). true until for loop stops, left , right each containing guard value.

another option, as seen here, loop until either left or right exhausted, have follow-up loops collect remaining values.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -