简体   繁体   English

在 Python Array 和 Numpy Array 中产生不同输出的排序方法

[英]Sorting method producing different output in Python Array versus Numpy Array

I have some code further below which is doing a merge sort.我在下面还有一些代码正在执行合并排序。 It was implemented using a python Array of ints (list of ints) as my initial test case.它是使用 Python 整数数组(整数列表)作为我的初始测试用例实现的。 This went well.这很顺利。 However, once this was working, I generated a random set of numbers to test further.然而,一旦这奏效,我就生成了一组随机数字来进一步测试。 This list is a numpy array.这个列表是一个 numpy 数组。 The merge sort does not work with the numpy array, the results look like repeated figures and like the reconstruction isn't working as intended.合并排序不适用于 numpy 数组,结果看起来像重复的数字,并且重建没有按预期工作。

My assumption is that the way the subdivided array is passed to mergesort and then recombined in memory is different between the two, and that is what is causing the issue.我的假设是,细分数组传递给归并排序然后在内存中重新组合的方式在两者之间是不同的,这就是导致问题的原因。 However, I am not certain.但是,我不确定。

Any thoughts?有什么想法吗?

example arrays: working with:示例数组:使用:

Array = [48,44,19,59,72,80,42,65,82,8,95,68]

not working with不与

unsorted = np.random.randint(1, 1000, 150)

The merge sort code:归并排序代码:

#function for merging two sub-arrays
def merge(left, right, Array):
    i = 0
    j = 0
    k = 0

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

        k = k+1

    while (i < len(left)):
        Array[k] = left[i]
        i = i+1
        k = k+1

    while (j < len(right)):
        Array[k] = right[j]
        j = j+1
        k = k+1
 
#function for dividing and calling merge function
def mergesort(Array):
    n = len(Array)
    if (n < 2):
        return

    mid = n / 2
    
    left = Array[0 : int(np.round(mid))]
    right  = Array[int(np.round(mid)) : n]
    print("array size = {}, leftsize= {}, rightsize= {}".format(n, len(left), len(right)))

    mergesort(left)
    mergesort(right)

    merge(left, right, Array)
    
    return Array

Then just need to call the following to compare the output:然后只需要调用以下来比较输出:

mergesort(Array)
mergesort(unsorted)

Add left = left.copy() at the start of merge , otherwise it's a view of Array so that writing into Array overwrites left .merge开始处添加left = left.copy() ,否则它是Array的视图,以便写入Array覆盖left

( right is also a view, but that's ok since you're not overwriting it faster than you're reading it) right也是一个视图,但没关系,因为您覆盖它的速度不会比阅读它的速度快)

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

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