合并python中的排序代码不起作用

时间:2018-01-24 18:17:37

标签: python python-3.x algorithm mergesort

在python中合并排序代码

每次尝试运行时,列表索引超出范围错误都会闪烁。 不知道到底发生了什么。我对python和算法的东西都是新手。请帮我调试一下。

def merge(m_list,first,middle,last):
    m_first = []
    m_last = []
    for each in range(first,middle):
        m_first.append(m_list[each])

    for each in range(middle,last+1):
        m_last.append(m_list[each])

    i=0
    j=0
    k=0

    while(i<middle and j<last-middle+1):
        if(m_first[i]<m_last[j]):
            m_list[k] = m_first[i]

            i +=1
        else:
            m_list[k] = m_last[j]

            j +=1
        k +=1

    print(m_list)

    while(i<middle):
        m_list[k] = m_first[i]
        k +=1
        i +=1

    while(j<last-middle+1):
        m_list[k] = m_last[j]
        k +=1
        j +=1

def merge_sort(m_list,first,last):
    if(first<last):
        middle = int(abs((first+last)/2))
        merge_sort(m_list,first,middle)
        merge_sort(m_list,middle+1,last)
        merge(m_list,first,middle,last)

    return(m_list)



merge_sort([1,4,6,2,3,5],0,5)
  

以下是代码

显示的错误
Traceback (most recent call last):
  File "merge_sort.py", line 48, in <module>
    merge_sort([1,4,6,2,3,5],0,5)
  File "merge_sort.py", line 41, in merge_sort
    merge_sort(m_list,middle+1,last)
  File "merge_sort.py", line 40, in merge_sort
    merge_sort(m_list,first,middle)
  File "merge_sort.py", line 42, in merge_sort
    merge(m_list,first,middle,last)
  File "merge_sort.py", line 15, in merge
    if(m_first[i]<m_last[j]):
IndexError: list index out of range

1 个答案:

答案 0 :(得分:0)

你错过了一些事情。增加k,初始化k并为条件设置适当的边界。 以下是工作代码。与你的比较,看看你错过了什么。

def merge(m_list,first,middle,last):
    m_first = []
    m_last = []
    for each in range(first,middle+1):
        m_first.append(m_list[each])

    for each in range(middle+1,last+1):
        m_last.append(m_list[each])

    i=0
    j=0
    k=first

    while(i<middle-first +1 and j<last-middle):
        if(m_first[i]<m_last[j]):
            m_list[k] = m_first[i]
            k +=1
            i +=1
        else:
            m_list[k] = m_last[j]
            k +=1
            j +=1

     print(m_list)

    while(i<middle-first +1):
        m_list[k] = m_first[i]
        k +=1
        i +=1

    while(j<last-middle):
        m_list[k] = m_last[j]
        k +=1
        j +=1

def merge_sort(m_list,first,last):
    if(first<last):
        middle = int(abs((first+last)/2))
        merge_sort(m_list,first,middle)
        merge_sort(m_list,middle+1,last)
        merge(m_list,first,middle,last)

    return(m_list)



print merge_sort([9,7,6,5,4,3],0,5)