# Introduction to Algorithms 第二章的问题

Problems 2-4: Inversions

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.

a List the five inversions of the array 〈2, 3, 8, 6, 1〉.

b What array with elements from the set {1, 2, . . . , n} has the most inversions? How many does it have?

c What is the relationship between the running time of insertion sort and the number of inversions in the input array? Justify your answer.

d 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.)

#include <iostream>
using namespace std;

int inversion_merge(int a[],int pre,int mid,int post,int count)
{
int * part1 = new int[mid-pre+1];
int * part2 = new int[post-mid];
int i,j;
for(i=0;i<mid-pre+1;i++){
part1[i] = a[pre+i];
}
for(i=0;i<post-mid;i++){
part2[i] = a[mid+1+i];
}
for(i=0,j=0;i<mid-pre+1&&j<post-mid;){
if(part1[i]>part2[j]){
a[pre+i+j]=part2[j];
++j;
count+=mid-pre+1-i;//根据移动位数得出inversion num
}
else{
a[pre+i+j]=part1[i];
++i;
}
}
if(i==mid-pre+1){
while(j<post-mid){
a[pre+i+j]=part2[j];
++j;
}
}
else{
while(i<mid-pre+1){
a[pre+i+j]=part1[i];
++i;
}
}
return count;
}
int inversion(int a[],int pre, int post, int count)
{
if(pre<post){
int mid = (pre+post)/2;
count=inversion(a,pre,mid,count);
count=inversion(a,mid+1,post,count);
count = inversion_merge(a,pre,mid,post,count);
return count;
}
return count;
}
int main(int argc, _TCHAR* argv[])
{
int a[] = {2,3,8,6,1};
int result = inversion(a,0,sizeof(a)/sizeof(int)-1,0);
cout<<"the result is: "<< result<<endl;
return 0;
}

...全文
63 点赞 收藏 2

2 条回复

darcymei 2004-07-23

gnefuil 2004-07-22

3.2w+