归并排序求逆序对python
时间: 2023-11-13 22:54:04 浏览: 139
归并排序求逆序对的Python代码如下:
```python
def merge_sort(arr):
if len(arr) <= 1:
return arr, 0
mid = len(arr) // 2
left, left_count = merge_sort(arr[:mid])
right, right_count = merge_sort(arr[mid:])
merged, merge_count = merge(left, right)
return merged, left_count + right_count + merge_count
def merge(left, right):
result = []
i, j, count = 0, 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
count += len(left) - i
result += left[i:]
result += right[j:]
return result, count
```
其中,`merge_sort` 函数返回排好序的数组和逆序对的数量,`merge` 函数用于合并两个有序数组并计算逆序对的数量。
阅读全文