#include <iostream>
#include <cstdio>
using namespace std;
int count = 0;
void merge(int a[], int first, int mid, int last, int temp[])
{
int i = first, j = mid+1, k = 0;
while(i <= mid&&j <= last)
{
if(a[i] > a[j])
{
temp[k++] = a[j++];
count += mid-i+1;
}
else
temp[k++] = a[i++];
}
while(i <= mid)
temp[k++] = a[i++];
while(j <= last)
temp[k++] = a[j++];
for(i = 0; i < k; i++)
{
a[first+i] = temp[i];
}
}
void mergesort(int source[], int temp[], int first, int last)
{
int mid = (first + last)/2;
if(first < last)
{
mergesort(source, temp, first, mid);
mergesort(source, temp, mid+1, last);
merge(source, first, mid, last, temp);
}
}
int main()
{
int n;
int a[100], b[100];
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> a[i];
}
mergesort(a, b, 0, n-1);
for(int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
cout << count;
}
Mergesort——归并排序
猜你喜欢
转载自blog.csdn.net/blackmail3/article/details/81257514
今日推荐
周排行