反转计数问题

时间:2012-11-06 17:13:27

标签: python algorithm mergesort inversion

有人能看到我使用合并排序方法实现反转计数器的任何问题吗?我得到了非常小的列表的正确值,但是当我导入100,000个左右的整数列表时,我得到了错误的值。我的实现是这样的:在合并期间,每次从列表right添加变量到列表left时,我都会通过n递增类计数器len(left)。我这样做,直到列表完全合并和排序,通过我对mergesort和inversions的理解,应该涵盖每个可能的反转。我哪里错了?

from collections import deque

m = []
f = open("IntegerArray.txt")
for line in f:
    m.append(line)

class InversionCount:

    def __init__(self, n):
        self.n = n
    def inversionMergeSort(self, m):
        if len(m) <= 1:
            return m
        half = len(m)/2
        left = m[0:half]
        right = m[half:]
        left = self.inversionMergeSort(left)
        right = self.inversionMergeSort(right)
        return self.inversionSort(left, right)

    def inversionSort(self, left, right):
        leftQueue = deque(i for i in left)
        rightQueue = deque(j for j in right)
        orderedList = []
        while len(leftQueue) > 0 or len(rightQueue) > 0:
            if len(leftQueue) > 0 and len(rightQueue) > 0:
                if leftQueue[0] < rightQueue[0]:
                    orderedList.append(leftQueue[0])
                    leftQueue.popleft()
                else:
                    orderedList.append(rightQueue[0])
                    self.n += len(leftQueue)
                    rightQueue.popleft()
            elif len(leftQueue) > 0:
                orderedList.append(leftQueue[0])
                leftQueue.popleft()
            elif len(rightQueue) > 0:
                orderedList.append(rightQueue[0])
                rightQueue.popleft()
        return orderedList

nInversions = InversionCount(0)
nInversions.inversionMergeSort(m)
print nInversions.n

0 个答案:

没有答案