【问题标题】:Python merge sort repeating numbersPython合并排序重复数字
【发布时间】:2020-10-17 08:53:46
【问题描述】:

我正在尝试学习如何进行合并排序。但是,当我运行此代码时,输​​出是错误的。作为参考,我正在从 tutorialspoint 学习。

代码是

import random

Listy = []

for x in range(0, 15):

    Listy.append(random.randint(1, 15))

Second = []

for x in range(0, 20):

    Second.append(None)

    #I needed to initialize an empty array

def merge(low, mid, high):

    l1 = low
    l2 = mid + 1
    i = low
    while l1 <= mid and l2 <= high:
        print("First ", l1)
        print("Second", l2)
        print(i, " is i")
        if Listy[l1] < Listy [l2]:
            print("True")
            Second[i] = Listy[l1]
            l1 = l1 + 1

        else:
            print("False")
            Second[i] = Listy[l1]
            l2 = l2 + 1
        i = i + 1


        
    while l1 <= mid:
        Second[i] = Listy[l1]
        i = i+1
        l1 = l1 + 1
    while l2 <= high:
        Second[i] = Listy[l2]
        i = i+1
        l2 = l2 + 1
    for x in range(low, high):
        Listy[x] = Second[low]
        low = low + 1
    print(Listy)
def sort(low, high):
    print("Recursion: ", low, " - ", high)
    if low < high:
        mid = int((low+high) / 2)
        sort(low, mid)
        sort(mid + 1, high)
        merge(int(low), int(mid), int(high))
    else:
        return
for x in Listy:

    print(x)

sort(0, 15)

print(Listy)

我不知道为什么,但输出一遍又一遍地重复数字。这是通过代码 [11, 11, 7, 13, 13, 13, 13, 11, 14, 15, 15, 15, 15, 15, 2, 11] 测试打印的数组。为什么会这样?

【问题讨论】:

    标签: python sorting merge


    【解决方案1】:

    好的,所以我假设您问的是为什么您的代码显然没有对数组进行排序,而不是为什么“排序”数组中有重复的数字。

    (如果您的问题实际上是为什么“排序”数组中有重复的数字:因为 random 不检查它是否已经创建了一个数字(您必须自己实施检查重复项)并且因为您的合并函数'条件是if ... &lt; ...: ... else: 等于if ... &lt; ... elif ... &gt;= ...:...)

    否则,我在某些地方更改了您的代码以使其正常工作,您的主要错误是range(lowerBound, upperBound) 返回一个数组,其中第一个元素是lowerBound,最后一个元素是upperBound - 1。详情请查看我的 cmets:

    在合并(...)中:

    if Listy[l1] < Listy [l2]:
                Second[i] = Listy[l1]
                l1 = l1 + 1
    
            else:
                #Second[i] = Listy[l1] --> your line, you had l1 again instead of l2
                Second[i] = Listy[l2]
                l2 = l2 + 1
            i = i + 1
    

    和:

    # for x in range(low, high): --> your line, range() creates a list where
    # the upper bound is not! included
    # so your range was one too short
    # This caused the wierd repeated numbers (it always forgot to merge the last element)
    for x in range(low, high+1):
        Listy[x] = Second[low]
        low = low + 1
    

    为了开始排序:

    # sort(0, 15) --> your line, 1 too long. again, range() returns a list
    # where the upper bound is not included and you need to set high to
    # the highest included index (14), not the length of Listy
    sort(0, 14)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-12
      • 1970-01-01
      • 2018-10-16
      • 2019-05-14
      • 2019-05-14
      • 2013-05-02
      相关资源
      最近更新 更多