归并排序(微改后便成为求逆序对数量的代码)

该代码展示了归并排序算法的实现,并通过修改部分代码实现计算逆序对的功能。归并排序是一种分治算法,通过递归将数组分为两半,再进行合并。在合并过程中,可以统计逆序对的数量。逆序对是指在数组中,数值较大的元素出现在数值较小的元素之前的组合。
摘要由CSDN通过智能技术生成

【归并排序算法代码】

下文源代码是归并排序的一种实现方法。若去掉其中的第26行语句 ans+=mid-ls+1;  及第42行语句 cout<<ans; 前的注释,并在第40行语句 for(int i=1; i<=n; i++) cout<<a[i]<<" "; 前添加注释之后,便成为求逆序对的代码。

#include <bits/stdc++.h>
using namespace std;
 
const int maxn=100005;
int a[maxn];
int t[maxn];
 
long long ans;
 
void merge_sort(int low,int high) {
	if(low>=high) return; //"low>=high" equivalent to "low==high"
 
	int mid=(low+high)>>1;
	merge_sort(low,mid);
	merge_sort(mid+1,high);
 
	for(int i=low; i<=high; i++) t[i]=a[i];
 
	int ls=low,hs=mid+1; //ls:low half interval's starting, hs:high half interval's starting
	for(int i=low; i<=high; i++) {
		if(ls>mid) a[i]=t[hs++];
		else if(hs>high) a[i]=t[ls++];
		else if(t[ls]<=t[hs]) a[i]=t[ls++];
		else {
			if(t[ls]>t[hs]) {
				//ans+=mid-ls+1;
				a[i]=t[hs++];
			}
		}
	}
}
 
int main() {
	int n;
	cin>>n;
	for(int i=1; i<=n; i++) cin>>a[i];
 
	merge_sort(1,n);
 
	for(int i=1; i<=n; i++) cout<<a[i]<<" ";
 
	//cout<<ans;
 
	return 0;
}
 
/*
in:
6
2 3 4 5 6 1
out:
1 2 3 4 5 6
in:
9
8 4 5 7 1 3 6 2 9
out:
1 2 3 4 5 6 7 8 9
*/


【参考文献】
https://blog.csdn.net/qionggaobi9328/article/details/105676962
https://blog.csdn.net/zpznba/article/details/88395447
https://blog.csdn.net/zpznba/article/details/83745205
https://blog.csdn.net/kevinmeanscool/article/details/87916085
https://blog.csdn.net/hnjzsyjyj/article/details/119767480

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值