Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
91 views
in Technique[技术] by (71.8m points)

python - How do I fix an out of index error in a 3 way merge sort?

I am currently writing a 3 way merge sort algorithm in python and have stumbled upon a list index out of range error when I run my code.

def merge_sort_algorithm(sort_list):
    
    if len(sort_list) < 2:
        return(sort_list)

    third = int(len(sort_list)/3)
    two_thirds = third * 2
    left = sort_list[:third]
    mid = sort_list[third:two_thirds]
    right = sort_list[two_thirds:]

    merge_sort_algorithm(left)
    merge_sort_algorithm(mid)
    merge_sort_algorithm(right)

    i = 0 #left
    j = 0 #mid
    k = 0 #right

    l = 0

    while i < len(left) and j < len(mid) and k < len(right) :
        if (left[i] < right[k] and left[i] < mid[j]):
            sort_list[l] = left[i]
            i += 1
        elif (mid[j] < left[l] and mid[j] < right[k]):
            sort_list[l] = mid[j]
            j += 1
        else:
            l += 1
    
    while i < len(left) and j < len(mid):
        if (left[i] < mid[j]):
            sort_list[l] = left[i]
            i += 1
        else:
            sort_list[l] = mid[j]
            j += 1

    while i < len(left) and k < len(right):
        if (left[i] < right[k]):
            sort_list[l] = left[i]
            i += 1
        else:
            sort_list[l] = right[k]
            k += 1

    while j < len(mid) and k < len(right):
        if (mid[j] < right[k]):
            sort_list[l] = mid[j]
            j += 1
        else:
            sort_list[l] = right[k]
            k += 1
    
    while i < len(left):
        sort_list[l] = left[i]
        i += 1
    
    while j < len(mid):
        sort_list[l] = mid[j]
        j += 1
    
    while k < len(right):
        sort_list[l] = right[k]
        k += 1

When the algorithm uses recursion to go to the elif statement elif (mid[j] < left[l] and mid[j] < right[k])

It gives me an error. I tried using a debugger but I'm not sure what I am doing wrong. Any help would be appreciated, thanks.

question from:https://stackoverflow.com/questions/65841473/how-do-i-fix-an-out-of-index-error-in-a-3-way-merge-sort

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

mid[j] < left[l] should be mid[j] < left[i]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...