利用归并排序求逆序对
2013-05-07 12:47
162 查看
归并排序原理:
将一个规模为n的问题分解为n个已经排序的子问题(此时每个子问题只有一个数),然后两两进行合并就可以得到原问题的解。
求逆序对事实上就是统计归并排序中位置交换的次数,简单起见,我们可以用一个全局变量m_Count来统计。
代码如下:
int m_Count=0;
void merge(int* a,int begin,int temp,int end)
{
int first =begin;
int *b=new int[end-begin+1];
for(int i=0;i<=end-begin;i++)
{
b[i]=0;
}
int j=temp+1,t=0;
while(begin<=temp)
{
if (a[begin]>a[j])
{
m_Count += temp-begin+1;//此步即在统计逆序对的个数
b[t++]=a[j];
if (j<end)
{
j++;
}
else
{
j++;
break;
}
}
else
{
b[t++]=a[begin++];
}
}
for(;begin<=temp;begin++)
{
b[t++]=a[begin];
}
for(;j<=end;j++)
{
b[t++]=a[j];
}
for(int i=first;i<=end;i++)
{
a[i]=b[i-first];
}
delete []b;
return;
}
void mergesort(int* a,int begin,int end)
{
if (begin<end)
{
int temp=begin+(end-begin)/2;
mergesort(a,begin,temp);
mergesort(a,temp+1,end);
merge(a,begin,temp,end);
}
return;
}
将一个规模为n的问题分解为n个已经排序的子问题(此时每个子问题只有一个数),然后两两进行合并就可以得到原问题的解。
求逆序对事实上就是统计归并排序中位置交换的次数,简单起见,我们可以用一个全局变量m_Count来统计。
代码如下:
int m_Count=0;
void merge(int* a,int begin,int temp,int end)
{
int first =begin;
int *b=new int[end-begin+1];
for(int i=0;i<=end-begin;i++)
{
b[i]=0;
}
int j=temp+1,t=0;
while(begin<=temp)
{
if (a[begin]>a[j])
{
m_Count += temp-begin+1;//此步即在统计逆序对的个数
b[t++]=a[j];
if (j<end)
{
j++;
}
else
{
j++;
break;
}
}
else
{
b[t++]=a[begin++];
}
}
for(;begin<=temp;begin++)
{
b[t++]=a[begin];
}
for(;j<=end;j++)
{
b[t++]=a[j];
}
for(int i=first;i<=end;i++)
{
a[i]=b[i-first];
}
delete []b;
return;
}
void mergesort(int* a,int begin,int end)
{
if (begin<end)
{
int temp=begin+(end-begin)/2;
mergesort(a,begin,temp);
mergesort(a,temp+1,end);
merge(a,begin,temp,end);
}
return;
}
相关文章推荐
- 利用归并排序求数列中逆序对个数
- 利用归并排序求数组中的逆序对
- 利用归并排序求逆序对
- poj 2299 利用归并排序求逆序数
- 利用归并排序求逆序数
- 归并排序及利用归并排序求逆序对数
- 求逆序对数(利用归并排序)
- 利用归并排序求逆序对
- 哈理工OJ 2224 逆序对问题(利用归并排序求逆序数对数)
- 利用归并排序求逆序数
- ACM:归并排序,以及利用归并排序思想求解逆序对数!
- 归并排序-逆序对的求解
- 归并排序与逆序对
- 逆序对问题的另一种经典解法:归并排序
- POJ-Ultra-QuickSort 归并排序求逆序对
- 九度OJ 1348 数组中的逆序对 -- 归并排序
- 剑指Offer 36题 数组中的逆序对 Java版 这个和归并排序一起看 对比差别在哪
- 剑指offer---数组中的逆序对(归并排序)PHP
- 使用归并排序求解数组逆序对个数
- 【归并排序】求逆序对的时候顺手写的,于是就顺手贴了,于是标题就长了