Sunday, 15 July 2012

algorithm - Merge Sort Problems - Python -



algorithm - Merge Sort Problems - Python -

what's wrong code? prints part of vect values. seems while loop breaks @ point. don't understand why.

def print_list(vect): in range(0, len(vect)): print(vect[i]) def merge_sort(vect): left = [] right = [] result = [] in range(0, int(len(vect)/2)): left.append(vect[i]) in range(int(len(vect)/2), len(vect)): right.append(vect[i]) left.sort() right.sort() = 0 j = 0 while < len(left) , j < len(right): if left[i] <= right[j]: result.append(left[i]) += 1 else: result.append(right[j]) j += 1 print(len(result)) homecoming result vect = [3, 1, 5, 7, 10, 2, 0] vect = merge_sort(vect)

well, error after while loop

while < len(left) , j < len(right): ...

it may (and would) either i < len(left) or j < len(right), need append appropriate part's suffix answer. it's easy

result += left[i:] result += right[j:]

explanation:

imagine merge procedure: have , j @ 0 @ start, , @ every step move 1 of them forward. when stop ? when 1 of them reaches end. let's has reached end. hereby added whole left part result, there still elements in right between j , len(right), have add together them reply too.

offtop:

you implementing merge sort, please have

left = merge_sort( left ) right = merge_sort( right )

instead of

left.sort() right.sort()

attention: have add together next check code @ origin of merge function avoid infinite recursion:

if len( vect ) == 1: homecoming vect

also in print_list function can use

print vect

or @ least

for x in vect print x

python algorithm sorting merge

No comments:

Post a Comment