简体   繁体   English

在python3中实现合并排序

[英]Implementing merge sort in python3

I don't know what's wrong here. 我不知道这是怎么回事。 can anyone help me do merge sort in python3.Please ,where did i go wrong....? 谁能帮我在python3中做合并排序。请,我哪里出错了...?

def merge_help(a,b):
    c=[]
    j=0
    i=0
    while(i<len(a) and j<len(b)):
        if(a[i]>=b[j]):
            c.append(b[j])
            j+=1
        elif(a[i]<=b[j]):
            c.append(a[i])
            i+=1
    while(j<len(b)):
        c.append(b[j])
        j+=1
    while(i<len(a)):
        c.append(a[i])
        i+=1
    return c
    def merge(a):
    if(len(a)>1):
        mid =len(a)//2
        l=a[:mid]
        r=a[mid:]
        merge(l)
        merge(r)
        merge_help(l,r)
    print(a)

merge([12,11,13,5,6,7]) doesn't work.... no errors but same list is returned back every recursive step merge([12,11,13,5,6,7])不起作用。...没有错误,但是每个递归步骤都返回相同的列表

You are not capturing the output of merge_help, so you are not actually changing the values in the 'a' list. 您没有捕获merge_help的输出,因此实际上并没有更改'a'列表中的值。

You are also attempting to do this in-place, which is not possible with merge sort. 您还尝试就地执行此操作,这对于合并排序是不可能的。

In your merge function, do this: 在您的合并功能中,执行以下操作:

def merge(a):
    if(len(a) > 1):
        # Divide the list in two
        mid = len(a)//2
        left_unsorted = a[:mid]
        right_unsorted = a[mid:]

        # Sort both halves
        left_sorted = merge(left_unsorted)
        right_sorted = merge(right_unsorted)

        # Merge the two sorted lists
        a_sorted = merge_help(left_sorted, right_sorted)
    else:
        a_sorted = a.copy()
    return a_sorted

Note: this does not sort the passed list; 注意:这不会对传递的列表进行排序; it only returns a sorted version. 它仅返回排序的版本。 So if you call it with orig_list, orig_list will be unchanged at the end. 因此,如果使用orig_list进行调用,则orig_list的结尾将保持不变。

You append the fields from a and b to c, but in the end you print a. 您将字段从a和b追加到c,但是最后打印a。 Maybe this is the problem. 也许这就是问题所在。

Array a is never edited 数组a永远不会编辑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM