• 全部
  • 问答

Introduction to Algorithms 第二章的问题

darcymei 2004-07-22 12:01:02
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.)

关于d 我的解法是
#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;
}
感觉有些牵强
不知道各位觉得思路应该如何?

...全文
58 点赞 收藏 2
写回复
2 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
darcymei 2004-07-23
这个...100分呢 各位能不能再给个别的方法..?
回复
gnefuil 2004-07-22
这样即可,没什么牵强的
回复
发帖
数据结构与算法
创建于2007-08-27

3.2w+

社区成员

数据结构与算法相关内容讨论专区
申请成为版主
帖子事件
创建了帖子
2004-07-22 12:01
社区公告
暂无公告