归并排序:数组中的逆序对。

 4 class Solution {
 5 public:
 6     int InversePairs(vector<int> data) {
 7         if(data.size()<=1) return 0;//如果少于等于1个元素,直接返回0
 8         int* copy=new int[data.size()];
 9         //初始化该数组,该数组作为存放临时排序的结果,最后要将排序的结果复制到原数组中
10         for(unsigned int i=0;i<data.size();i++)
11             copy[i]=0;
12         //调用递归函数求解结果
13         int count=InversePairCore(data,copy,0,data.size()-1);
14         delete[] copy;//删除临时数组
15         return count;
16     }
17      //程序的主体函数
18     int InversePairCore(vector<int>& data,int*& copy,int start,int end)
19     {
20         if(start==end)
21         {
22             copy[start]=data[start];
23             return 0;
24         }
25         //将数组拆分成两部分
26         int length=(end-start)/2;//这里使用的下标法,下面要用来计算逆序个数;也可以直接使用mid=(start+end)/2
27         //分别计算左边部分和右边部分
28         int left=InversePairCore(data,copy,start,start+length)%1000000007;
29         int right=InversePairCore(data,copy,start+length+1,end)%1000000007;
30         //进行逆序计算
31         int i=start+length;//前一个数组的最后一个下标
32         int j=end;//后一个数组的下标
33         int index=end;//辅助数组下标,从最后一个算起
34         int count=0;
35         while(i>=start && j>=start+length+1)
36         {
37             if(data[i]>data[j])
38             {
39                 copy[index--]=data[i--];
40                 //统计长度
41                 count+=j-start-length;
42                 if(count>=1000000007)//数值过大求余
43                     count%=1000000007;
44             }
45             else
46             {
47                 copy[index--]=data[j--];
48             }
49         }
50         for(;i>=start;--i)
51         {
52             copy[index--]=data[i];
53         }
54         for(;j>=start+length+1;--j)
55         {
56             copy[index--]=data[j];
57         }
58         //排序
59         for(int i=start; i<=end; i++) {
60             data[i] = copy[i];
61         }
62         //返回最终的结果
63         return (count+left+right)%1000000007;
64     }
65 };

猜你喜欢

转载自www.cnblogs.com/icehole/p/12129545.html
今日推荐