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;
}
感觉有些牵强
不知道各位觉得思路应该如何?

...全文
104 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
darcymei 2004-07-23
  • 打赏
  • 举报
回复
这个...100分呢 各位能不能再给个别的方法..?
gnefuil 2004-07-22
  • 打赏
  • 举报
回复
这样即可,没什么牵强的

33,008

社区成员

发帖
与我相关
我的任务
社区描述
数据结构与算法相关内容讨论专区
社区管理员
  • 数据结构与算法社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧