【算法】测试数组逆序对个数算法(C++源码)

一、任务描述

给定一个整数数组A=(a0, a1,…,an-1),若i<j且ai > aj,则<ai,aj>就为一个逆序对。例如数组(3,1,4,5,2)的 逆序对有<3,1>, < 3,2>,<4,2>,<5,2>。请编写并测试 求A中逆序对个数的算法,并分析其时间复杂度。

二、步骤描述

随机生成数暴力求解,时间复杂度O(n²)

三、运行结果截图

【算法】测试数组逆序对个数算法(C++源码)_逆序对


【算法】测试数组逆序对个数算法(C++源码)_算法_02


【算法】测试数组逆序对个数算法(C++源码)_算法_03

四、源代码(C++)

#include<iostream>
#include<ctime>
#include<Windows.h>

using namespace std;

int main()
{
DWORD start_time=GetTickCount();
srand(time(NULL));
int n;
cout<<"Please enter the number of array size :";
cin>>n;
int a[n],i,j,count=0;
cout<<n<<" random arrays are being generated,please wait !"<<endl;
for(i=0;i<n;i++)
{
a[i]=rand()%10;
}
cout<<n<<" random arrays generation completed !"<<endl;
cout<<n<<" random arrays print :";
for(i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
cout<<"<"<<a[i]<<","<<a[j]<<">"<<" ";
count++;
}
}
}
cout<<endl;
cout<<"The number of reverse alignment is :"<<count<<endl;
DWORD end_time = GetTickCount();
cout<<"The run time is :"<<(end_time-start_time)<<"ms!"<<endl;
return 0;
}