如果用最hick的方法去求那么就是O(n^2)的复杂度,如果想优化的话,用归并排序的方法分治处理。
主要思想:总逆序=左边逆序+右边逆序+左边右边分别排序后的逆序
#include<stdio.h>
#include<stdlib.h>
using namespace std;
//用归并排序的思想来求,归并排序为O(nlogn)的时间复杂度,比暴力的O(n^2)会好。
int merge(int *a, int low, int mid, int high)
{
int l_size = mid-low+1;
int r_size = high-mid;
int *l_list = (int *)malloc(l_size*sizeof(int));
int *r_list = (int *)malloc(r_size*sizeof(int));
int i, j, k;
for(i=0; i<l_size; i++)
l_list[i] = a[low+i];
for(i=mid+1; i<=high; i++)
r_list[i-mid-1] = a[i];
k = low;
int count = 0;
for(i=0, j=0; i<l_size && j<r_size;)
{
if(l_list[i]<=r_list[j])
a[k++] = l_list[i++];
else
{
for(int tmp=i;tmp<l_size;tmp++)
printf("(%d,%d) ", l_list[tmp],r_list[j]); //打印逆序对;
a[k++] = r_list[j++];
count += l_size-i; //从i到l_size-1,所以是l_size-1-i+1 = l_size-i个逆序对
}
}
while(i<l_size)
a[k++] = l_list[i++];
while(j<r_size)
a[k++] = r_list[j++];
free(l_list);
free(r_list);
return count;
}
int reverse_order(int *a, int low, int high)
{
int count = 0;
if(low < high)
{
int mid = (low+high)>>1;
//总逆序=左边逆序+右边逆序+左边右边分别排序后的逆序
count += reverse_order(a, low, mid);
count += reverse_order(a, mid+1, high);
count += merge(a, low, mid, high);
}
return count;
}
int main(void)
{
//int a[] = {5,4,3,2,1};
int a[] = {1,2,4,3,0};
int n = sizeof(a)/sizeof(a[0]);
printf("原数组为 :\n");
for(int i=0; i<n; i++)
printf("%d ",a[i]);
printf("\n打印逆序: \n");
int count=reverse_order(a, 0, n-1);
printf("\nreverse_order count: %d\n", count);
printf("排序后数组为 :\n");
for(int i=0; i<n; i++)
printf("%d ", i,a[i]);
printf("\n");
system("pause");
return 0;
}