/*
快速排序 和 归并排序求逆序对
*/
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<cmath>
#include <algorithm>
using namespace std;
const int MAX = 500;
int A[MAX];
int n;
int tot;
int T[MAX];
int merge_sort(int p, int q)
{
int cnt = 0;
if(q-p > 1) {
int m = p + (q-p)/2;
cnt += merge_sort(p, m);
cnt += merge_sort(m, q);
int x = p, y = m, i = p;
while(x<m || y<q) {
tot++;
if(y>=q || (x<m && A[x]<=A[y])) {
T[i++] = A[x++];
} else {
cnt += (m-x);
T[i++] = A[y++];
}
}
for(int i=p; i<q; i++) {
tot++;
A[i] = T[i];
}
}
return cnt;
}
int patition(int p, int q)
{
int key = A[q-1];
int j=p-1;
for(int i=p; i<q-1; i++) {
tot++;
if(A[i] < key) {
swap(A[i], A[++j]);
}
}
swap(A[++j], A[q-1]);
return j;
}
void quick_sort(int p, int q)
{
if(q-p > 1) {
int m = patition(p, q);
quick_sort(p, m);
quick_sort(m+1, q);
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
//freopen("merge_sort.txt", "w", stdin);
#endif
while(scanf("%d", &n) == 1) {
for(int i=0; i<n; i++) {
scanf("%d", &A[i]);
}
printf("%d: ", n);
for(int i=0; i<n; i++) {
printf("%d ", A[i]);
}
printf("\n");
tot = 0;
//quick_sort(0, n);
//printf("time:%d\n", tot);
int ret = merge_sort(0, n);
printf("re_order: %d\n", ret);
printf("time:%d\n", tot);
for(int i=0; i<n; i++) {
printf("%d ", A[i]);
}
}
return 0;
}
算法竞赛入门经典 快速排序和并归排序
最新推荐文章于 2020-07-29 20:20:28 发布