思想:递归分治
#include<bits/stdc++.h>
#define int long long
using namespace std;
int arr[100];
int res = 0;
void _merge(int left,int right,int mid){
int *copy = new int [right-left+1];
for(int i =left;i<=right;i++){
copy[i-left]=arr[i]; // copy拷贝的要使用的那一段原数组,且下标从0开始
}
int i =left; int j = mid+1;
for(int k=left;k<=right;k++){//k下标为原数组的下标
if(i>mid)
{
arr[k] = copy[j-left];
j++;
}
else if(j>right){
arr[k] = copy[i-left];
i++;
}
else if(copy[i-left]<=copy[j-left]){//左区间的数小于右区间的数 将左区间的数插入
arr[k]=copy[i-left];
i++;
}
else{
arr[k]=copy[j-left];
j++;
//res += mid - i+1;求逆序数
}
}
delete [] copy;
}
void dfs(int left,int right){
if(left>=right)return;
int mid = (right + left)/2;
dfs(left,mid);
dfs(mid+1,right);
_merge(left, right, mid);
}
void solve(){
int n;cin>>n;
for(int i =0;i<n;i++)cin>>arr[i];
dfs(0, n-1);
for(int i =0;i<n;i++)cout<<arr[i]<<" ";
}
signed main() {
//ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int _ = 1;
//cin >> _;
while (_--) {
solve();
}
return 0;
}
dfs理解