解题思路:
选择排序铁定超时,归并排序改进一下用进去
注意事项:
num = num + 1 + mid -i#关键所在,mid-i 归并过程省略一部分的交换,所以要加上去
参考代码:
import copy
n=int(input())
nums=list(map(int,input().split()))
num=0
def merge_sort(nums,left,right):
if right==left:#单个数返回
return
mid=(left+right)>>1
merge_sort(nums,left, mid)
merge_sort(nums,mid+1,right)
sort = []
i=left
j=mid+1
while i <= mid and j <= right:
global num
if nums[i] <= nums[j]:
sort.append(nums[i])
i += 1
else:
sort.append(nums[j])
j += 1
num = num + 1 + mid -i#关键所在,mid-i 归并过程省略一部分的交换,所以要加上去 sort.extend(nums[i: mid + 1])
sort.extend(nums[j: right + 1])
nums[left:right+1]=copy.deepcopy(sort)
merge_sort(nums,0,n-1)
print(num)
0.0分
0 人评分