首页 > 代码库 > 【剑指offer】数组中的逆序对

【剑指offer】数组中的逆序对

# @left part: [start, mid]
# @right part: (mid, end]
def merge(data, start, mid, end):
	if mid < start or end < mid:
		return 0
	reverse = 0
	'''
	 	@ for start, it play as the start index of left part, and mid 
		@ play as the end index of left part;
		@ mid + 1 (st2) play as the start index of right part, and end
		@ play as the end index of right part.
	'''
	#@ start of right part
	st2 = mid + 1
	while start <= mid and st2 <= end:
		if data[start] > data[st2]:
			# move data[st2] to start, and data[start, - 1]
			# move back by 1
			data.insert(start, data.pop(st2))
			reverse += st2 - start
			# [start, mid] move back by one, so start = start + 1 
			# and mid = mid + 1
			start += 1
			mid += 1
			# same as start & mid, move back by 1
			st2 += 1
		else:
			# no insert or move, so start = start + 1
			start += 1
	return reverse

def mergeSortWithCount(data, start, end):
	#just one item or Node, return dirctly
	if len(data) <= 1 or end <= start: 
		return 0
	mid = (start + end) >> 1

	#@ reversepair number of left part
	left = mergeSortWithCount(data, start, mid)

	# reversepair number of right part
	right = mergeSortWithCount(data, mid + 1, end)

	# toal count of reverse pair = left + right + {merger(left, right)}
	return merge(data, start, mid, end) + left + right
	

这个题,还可以通过线段树来实现,有兴趣的可以找一些线段树的题练一练。下面的链接是我学习线段树的第一个博客。

http://www.notonlysuccess.com/index.php/segment-tree/