在数组中的两个数如果前一个数大于后面的数,则这两个数组成逆序对。
解题思路:将数组中的元素两两划分为单一数组元素,用high1和high2分别表示相邻两个数组中末尾元素的位置,如果数组1中的high1的元素大于数组2中high2的元素,则high1与数组2中的所有元素构成逆序对(数组1和数组2均为递增数组),统计逆序对个数,high1--;否则,high2--;同时对数组1和数组2中的元素作归并操作,使归并后的数组为递增数组。具体代码如下:
// ConsoleApplication57.cpp : 定义控制台应用程序的入口点。
//归并排序的应用--输出逆序对
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
int b[100];
//归并操作
void Merge(int *a, int low, int mid,int high, int &count){
int k = mid;
int j = high;
int m = high;
for (int i = low; i <= high; i++)
b[i] = a[i];
while (low <= k && high>mid){
if (b[k] > b[j]){
count=count+(j-mid);//统计逆序对个数
for (int jj = j; jj > mid; jj--)
cout <<"(" <<b[k] <<" " <<b[jj]<<")"<<" " << endl;
//cout << endl;
a[m--] = b[k--];
}
else{
a[m--] = b[j--];
}
}
while (low <= k){
//count++;
a[m--] = b[k--];
}
while (j > mid){
//count++;
a[m--] = b[j--];
}
}
void MergeSort(int *a, int low, int high, int &count){
if (low < high){
int mid = (low + high) / 2;
int count1 = 0, count2 = 0, count3 = 0;
MergeSort(a, low, mid, count1);
MergeSort(a, mid + 1, high, count2);
Merge(a, low, mid, high, count3);
count = count1 + count2 + count3;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[4] = { 7, 5, 6, 4 };
int ccouont=-1;
cout << "逆序对:" << endl;
MergeSort(a, 0, 3, ccouont);
cout <<"逆序个数:"<< ccouont << endl;
system("pause");
return 0;
}
逆序对:
(7 5)
(6 4)
(7 6)
(7 4)
(5 4)
逆序个数:5
请按任意键继续. . .