简体   繁体   English

在 python 中实现归并排序

[英]Implementing merge-sort in python

I am trying to implement the merge-sort algorithm in Python 3. Here's the function that implements the merge part of the algorithm:我正在尝试在 Python 3 中实现合并排序算法。这是实现算法合并部分的 function:

def Merge(A,p,q,r):
n1 = q - p + 1
n2 = r - q

#We first populate two lists that contain the sorted subsequences A[p,...,q] and A[q+1,...,r]
L = []
R = []

for index in range(n1):
    L.append(A[index + p])

for index in range(n2):
    R.append(A[index + q + 1])

#We now overwrite the A[p,..,q,...r] section of the list by comparing the 'top-most'
#elements in the lists l and R and putting the smaller element in the corresponding
#entry in A. If one of the list is fully exposed/no longer available, we simply put the 
#remaining list's elements in the corresponding positions in A.

i = 0
j = 0

for k in range(r - p + 1 ):

    if i > n1-1:
        A[k] = R[j]
        j = j + 1

    elif j > n2-1:
        A[k] = L[i]
        i = i + 1

    elif L[i] < R[j]:
        A[k] = L[i]
        i = i + 1

    else:
        A[k] = R[j]
        j = j + 1 

return A   

I have tested this function and it runs fine: as long as the subarrays A[p,q] and A[q+1,r] are sorted, the whole array A[p,r] will be sorted correctly.我已经测试了这个 function 并且它运行良好:只要对子数组 A[p,q] 和 A[q+1,r] 进行排序,整个数组 A[p,r] 就会正确排序。 I now try and implement a divide and conquer approach to merge a large enough list.我现在尝试实施一种分而治之的方法来合并足够大的列表。

import math

def Merge_Sort(A,p,r):

if p == r:

    return A

if p < r:

    q = math.floor((p+r)/2)
    Merge_Sort(A,p,q)
    Merge_Sort(A,q+1,r)
    Merged_List = Merge(A,p,q,r)

return Merged_List

But I get erroneous answers when I run it.但是当我运行它时,我得到了错误的答案。 Here's an example:这是一个例子:

#We now analyze the merge sort algorithm.
A = [1,7,9,3]
B = Merge_Sort(A,0,3)
print(B)

The output is output 是

[3, 9, 3, 9]

I am probably making some obvious/stupid mistake in the implementation of the divide and conquer bit.我可能在实现分而治之时犯了一些明显/愚蠢的错误。 Suggestions?建议?

The error is in the assignments to A[k] .错误出在对A[k]的分配中。 They should be changed to assignments to A[p+k] .它们应该更改为对A[p+k]的分配。

Note that L and R can be defined using the following syntax (no explicit loop):请注意, LR可以使用以下语法定义(无显式循环):

L = A[p:q+1]
R = A[q+1:r+1]

To be consistent with how native functions work in Python (eg list.extend ), your two functions should not return the list.为了与本机函数在 Python(例如list.extend )中的工作方式保持一致,您的两个函数不应返回列表。 They mutate the list that you pass as argument, and so to avoid confusion, it is better not to return it: it could make users of your code think that the function has no side effects.它们会改变您作为参数传递的列表,因此为避免混淆,最好不要返回它:它可能会使您的代码用户认为 function 没有副作用。

In Merge Sort Algorithm, We first divide the array into two parts recursively, then sort each part and merge them recursively.So, Its a divide and conquer algorithm.在合并排序算法中,我们首先将数组递归地分成两部分,然后对每一部分进行排序并递归合并。所以,它是一种分治算法。

MergeSort(arr[], l,  r)
If r > l
     1. Find the middle point to divide the array into two halves:  
             middle m = (l+r)/2
     2. Call mergeSort for first half:   
             Call mergeSort(arr, l, m)
     3. Call mergeSort for second half:
             Call mergeSort(arr, m+1, r)
     4. Merge the two halves sorted in step 2 and 3:
             Call merge(arr, l, m, r)

I think your code have problem in the merge function.Where you should assign the elements of array L and array R.我认为您的代码在合并 function 中存在问题。您应该在哪里分配数组 L 和数组 R 的元素。 Your starting index is p, Therefore you should assign L[i] and R[i] to A[p+k] instead of A[k].您的起始索引是 p,因此您应该将 L[i] 和 R[i] 分配给 A[p+k] 而不是 A[k]。 If you still have doubts regarding merge sort refer to Merge Sort .如果您对归并排序仍有疑问,请参阅归并排序 hope this solves all your queries.希望这能解决您的所有疑问。 Thanks谢谢

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

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