归并排序是分治算法的实例之一。
利用归并排序可以直接计算出数据中逆序数的对数,并且时间复杂度并不大(O(nlogn)的时间复杂度)。
下面的程序,读入一列txt文件,并计算文件中逆序数对的个数。
txt文件中,数据只有一列,且都是整数,并且所有数据中没有重复数字。

#-*- coding:utf-8 -*-

class Ivrs_num(object):
    def __init__(self, filename):
        self.count = 0
        self.filename = filename

    def inverse_count(self):
        data = self.load_txt()
        def merge_sort(data):

            if len(data)<2:
                return data

            left = merge_sort(data[:(len(data)//2)])
            right = merge_sort(data[(len(data)//2):])
            idx_left = idx_right = 0
            result = []
            while idx_left < len(left) and idx_right < len(right):
                if left[idx_left] <= right[idx_right]:
                    result.append(left[idx_left])
                    idx_left += 1
                else:
                    result.append(right[idx_right])
                    idx_right += 1
                    self.count += len(left)-idx_left
            while idx_left < len(left):
                result.append(left[idx_left])
                idx_left += 1

            while idx_right < len(right):
                result.append(right[idx_right])
                idx_right += 1
            return result
        merge_sort(data)
        return self.count

    def load_txt(self):
        int_list = []
        with open(self.filename) as f:
            for line in f:
                int_list.append(int(line))
        return int_list






if __name__ == '__main__':

    m = Ivrs_num('UniqueIntegerArray.txt')

    print(m.inverse_count())