This repository has been archived by the owner on Dec 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Count_Invertion.cpp
76 lines (73 loc) · 1.63 KB
/
Count_Invertion.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*************************************************************************
> File Name: Count_Invertion.cpp
> Author: GZ
> Mail: 194463810@qq.com
> Created Time: 2018年03月13日 星期二 18时44分15秒
************************************************************************/
#include<iostream>
#include<queue>
#include<time.h>
#include<stdlib.h>
using namespace std;
const int MaxSize = 5;
void Merge(int s[], int low, int middle, int high, int &cnt);
void MergeSort(int s[], int low, int high, int &cnt);
int main(void)
{
int r[MaxSize];
cout << "请输入" << MaxSize << "个数\n$:";
for (int i = 0; i < MaxSize; i++)
cin >> r[i];
int count = 0;
MergeSort(r, 0, MaxSize - 1, count);
cout << "逆序数为:" << count << endl;
cout << endl;
return 0;
}
/*使用队列*/
void MergeSort(int s[], int low, int high, int &cnt)
{
int middle;
if (low < high)
{
middle = (low + high) / 2;
MergeSort(s, low, middle, cnt);
MergeSort(s, middle + 1, high, cnt);
Merge(s, low, middle, high, cnt);
}
}
void Merge(int s[], int low, int middle, int high, int &cnt)
{
int i;
queue<int> buffer1;
queue<int> buffer2;
for (i = low; i <= middle; i++)
buffer1.push(s[i]);
for (i = middle + 1; i <= high; i++)
buffer2.push(s[i]);
i = low;
while (!(buffer1.empty() || buffer2.empty()))
{
if (buffer1.front() <= buffer2.front())
{
s[i++] = buffer1.front();
buffer1.pop();
}
else
{
cnt += buffer1.size();
s[i++] = buffer2.front();
buffer2.pop();
}
}
while (!buffer1.empty())
{
s[i++] = buffer1.front();
buffer1.pop();
}
while (!buffer2.empty())
{
s[i++] = buffer2.front();
buffer2.pop();
}
}