Let
be a list of n distinct input integers. We call the pair (i, j) an inversion if i < j and
. Give a divide-and-conquer algorithm that reports in
time the total number of inversions in the input list. Explain why your algorithm works and why it runs in
time.
设A[1..n]是一个包含n个不同数的数组。如果在i < j的情况下,有A[i] > A[j],则(i, j)就称为A中的一个逆序对(inversion)。给出一个算法,它能用O(n log n)的最坏运行时间,确定n个元素的任何排列中逆序对的数目。
合并数列(1,3,5)与(2,4)的时候:
这样就完成了逆序数对的统计,归并排序的时间复杂度是O(N * LogN),因此这种从归并排序到数列的逆序数对的解法的时间复杂度同样是O(N * LogN)
def merge_sort(data):
if len(data) <= 1:
return data
index = len(data) // 2
lst1 = data[:index]
lst2 = data[index:]
left = merge_sort(lst1)
right = merge_sort(lst2)
return merge(left, right)
def merge(lst1, lst2):
"""to Merge two list together"""
list = []
while len(lst1) > 0 and len(lst2) > 0:
data1 = lst1[0]
data2 = lst2[0]
if data1 <= data2:
list.append(lst1.pop(0))
else:
global num
num = num + 1
list.append(lst2.pop(0))
if len(lst1) > 0:
list.extend(lst1)
else:
list.extend(lst2)
return list
num = 0
arr = [1, 3, 5, 2, 4]
print(merge_sort(arr))
print(num)
输出结果为
[1, 2, 3, 4, 5] 3
…
所以时间复杂度为