算法导论上Problems 2-4是一道求逆序数个数的问题,原题目是这样的:
Let A[1 ‥ n] be an array of n distinct numbers. If i < j and A[i] > A[j], then the pair (i, j) is called an inversion of A.
-
List the five inversions of the array 〈2, 3, 8, 6, 1〉.
-
What array with elements from the set {1, 2, . . . , n} has the most inversions? How many does it have?
-
What is the relationship between the running time of insertion sort and the number of inversions in the input array? Justify your answer.
-
Give an algorithm that determines the number of inversions in any permutation on n elements in Θ(n lg n) worst-case time. (Hint: Modify merge sort.)
下面是根据题目提示,修改归并排序后的代码
1: #include <iostream>
2: #include <vector>
3: using namespace std;
4:
5: template<typename T>
6: int mergeInversions(vector<T>& array,vector<T>& tempArray,int left,int mid,int right)
7: {
8: int l = left,r = mid+1;
9: int i =l;
10: int count=0;
11:
12: while(l<=mid&&r<=right)
13: {
14: //if a inversion found
15: if(array[l]>array[r])
16: {
17: //In left section ,for all the elements right to array[l], counter will count.
18: count+=mid-l+1;
19: }
20:
21: if(array[l]<=array[r])
22: tempArray[i++] = array[l++];
23: else
24: tempArray[i++] = array[r++];
25: }
26:
27: //copy the remaining elements in L and R to tempArray.
28: while(l<=mid)
29: tempArray[i++]= array[l++];
30: while (r<=right)
31: tempArray[i++] = array[r++];
32: //copy the sorted elements back to the original array.
33: for(i=left;i<=right;i++)
34: array[i] = tempArray[i];
35: return count;
36: }
37:
38: template<typename T>
39: int countInversions(vector<T>& array,vector<T>& tempArray,int left,int right)
40: {
41: int count = 0;
42: if(left < right)
43: {
44: int mid = (left + right)/2;
45: count += countInversions(array,tempArray,left,mid);
46: count += countInversions(array,tempArray,mid+1,right);
47: count += mergeInversions(array,tempArray,left,mid,right);
48: }
49: return count;
50: }
51:
52: template<typename T>
53: int countInversions(vector<T>& array)
54: {
55: vector<T> tempArray(array.size());//A auxiliary vector will be used in merge function.
56: return countInversions(array,tempArray,0,array.size()-1);
57: }
58:
59: int main()
60: {
61: vector<int> array(5);
62: array[0]= 5;
63: array[1]= 4;
64: array[2]= 3;
65: array[3]= 2;
66: array[4]= 1;
67: cout<<"Number of inversions:";
68: cout<<countInversions<int>(array)<<endl;
69: }