如何在python中添加合并排序的比较计数器?

时间:2017-03-05 12:58:07

标签: python algorithm sorting merge comparison

我正在使用的代码如下。

我想在此代码中添加一个比较计数器,但我现在拥有的那个将显示与元素数量相同的数字。

def MergeSort(argShuffledList):
    intNumOfComp = 0
    if len(argShuffledList)>1:
        intMidValue = len(argShuffledList)//2
        listLeftHalf = argShuffledList[:intMidValue]
        listRightHalf = argShuffledList[intMidValue:]

        MergeSort(listLeftHalf)
        MergeSort(listRightHalf)

        i=0
        j=0
        k=0
        while i < len(listLeftHalf) and j < len(listRightHalf):
            if listLeftHalf[i] < listRightHalf[j]:
                argShuffledList[k]=listLeftHalf[i]
                i=i+1
                intNumOfComp += 1
            else:
                argShuffledList[k]=listRightHalf[j]
                j=j+1
                intNumOfComp += 1

            k=k+1

        while i < len(listLeftHalf):
            argShuffledList[k]=listLeftHalf[i]
            i=i+1
            k=k+1
            intNumOfComp += 1

        while j < len(listRightHalf):
            argShuffledList[k]=listRightHalf[j]
            j=j+1
            k=k+1
            intNumOfComp += 1

    return argShuffledList, "Comparison Count: " + str(intNumOfComp)

1 个答案:

答案 0 :(得分:0)

您进行了递归,因此您没有计算左半部列表和右半部分列表的比较。这是改革正确的代码。

def MergeSort(argShuffledList):
    intNumOfComp = 0

    if len(argShuffledList)>1:
        intMidValue = len(argShuffledList)//2
        listLeftHalf = argShuffledList[:intMidValue]
        listRightHalf = argShuffledList[intMidValue:]

        left_part = MergeSort(listLeftHalf)
        right_part = MergeSort(listRightHalf)

        intNumOfComp += left_part[1] + right_part[1]

        i=0
        j=0
        k=0
        while i < len(listLeftHalf) and j < len(listRightHalf):
            intNumOfComp += 1
            if listLeftHalf[i] < listRightHalf[j]:
                argShuffledList[k]=listLeftHalf[i]
                i =i+1

            else:
                argShuffledList[k]=listRightHalf[j]
                j=j+1

            k=k+1

        while i < len(listLeftHalf):
            argShuffledList[k]=listLeftHalf[i]
            i=i+1
            k=k+1
            intNumOfComp += 1

        while j < len(listRightHalf):
            argShuffledList[k]=listRightHalf[j]
            j=j+1
            k=k+1
            intNumOfComp += 1

    return argShuffledList, intNumOfComp