一、算法学习
1、归并排序
代码:
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<memory>
#include<functional>
using namespace std;
void merge(int a[],int l,int mid,int r)
{
//cout<<"l:"<<l<<endl;
//cout<<"r:"<<r<<endl;
//cout<<"mid:"<<mid<<endl;
int help[100];
int p1 = l;
int p2 = mid+1;
int i = 0;
while(p1<=mid&&p2<=r)
{
if(a[p1]<=a[p2])
{
help[i++] = a[p1++];
}
else
{
help[i++] = a[p2++];
}
}
while(p1<=mid)
{
help[i++] = a[p1++];
}
while(p2<=r)
{
help[i++] = a[p2++];
}
int len = r-l+1;
for(int j = 0;j<len;++j)
a[l+j] = help[j];
/*for(int i = 0;i<5;++i)
cout<<a[i]<<endl;
cout<<"finish!"<<endl;*/
}
//归并排序
void mergesort(int a[],int l,int r)
{
if(l==r)
return;
int mid = l+((r-l)>>1);
//注意这里计算终点位置的时候,由于加法运算的优先级比移位运算高
//所以需要在移位运算上打上括号
//这样写的原因是移位运算的时间代价比除法高
mergesort(a,l,mid);//左边部分有序
mergesort(a,mid+1,r);//右边部分有序
//cout<<"sort"<<endl;
merge(a,l,mid,r);//将整体进行合并
}
int main()
{
int a[5] = {3,4,6,7,1};
mergesort(a,0,4);
for(int i = 0;i<5;++i)
cout<<a[i]<<endl;
return 0;
}
在使用归并排序解决问题的时候,在出现左边的数和右边的数相等的时候,要根据具体问题决定拷贝左边的数还是右边的数。
小和问题:
转化为求一个数的右边有多少个数比这个数大
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<memory>
#include<functional>
using namespace std;
int res = 0;
int help[100];
//小和问题
void merge(int a[],int l,int mid, int r)
{
int p1 = l;
int p2 = mid+1;
int i = 0;
int help[100];
memset(help,0,sizeof(help));
while(p1<=mid&&p2<=r)
{
if(a[p1]<a[p2])
{
res += a[p1]*(r-p2+1);
help[i++] = a[p1++];
}
if(a[p1]>=a[p2])
{
help[i++] = a[p2++];
}
}
while(p1<=mid)
{
help[i++] = a[p1++];
}
while(p2<=r)
{
help[i++] = a[p2++];
}
int len = r-l+1;
for(int j = 0;j<len;++j)
{
a[l+j] = help[j];
}
}
void mergesort(int a[],int l,int r)
{
if(l == r)
return;
int mid = l + ((r-l)>>1);
mergesort(a,l,mid);
mergesort(a,mid+1,r);
//进行排序之后要进行合并
merge(a,l,mid,r);
}
int main()
{
int a[5] = {1,3,4,2,5};
mergesort(a,0,4);
for(int i = 0;i<5;++i)
cout<<a[i]<<endl;
cout<<"res:"<<res<<endl;
return 0;
}
逆序问题:
转化为一个数的左边有多少个数比自身大
#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<memory>
#include<functional>
using namespace std;
int res = 0;
int help[100];
//求逆序对
void merge(int a[],int l,int mid, int r)
{
int p1 = l;
int p2 = mid+1;
int i = 0;
int help[100];
memset(help,0,sizeof(help));
while(p1<=mid&&p2<=r)
{
if(a[p1]<=a[p2])
{
//res += a[p1]*(r-p2+1);
help[i++] = a[p1++];
}
if(a[p1]>a[p2])
{
res += mid-p1+1;
help[i++] = a[p2++];
}
}
while(p1<=mid)
{
help[i++] = a[p1++];
}
while(p2<=r)
{
help[i++] = a[p2++];
}
int len = r-l+1;
for(int j = 0;j<len;++j)
{
a[l+j] = help[j];
}
}
void mergesort(int a[],int l,int r)
{
if(l == r)
return;
int mid = l + ((r-l)>>1);
mergesort(a,l,mid);
mergesort(a,mid+1,r);
//进行排序之后要进行合并
merge(a,l,mid,r);
}
int main()
{
int a[5] = {1,3,4,2,5};
mergesort(a,0,4);
for(int i = 0;i<5;++i)
cout<<a[i]<<endl;
cout<<"res:"<<res<<endl;
return 0;
}
2、堆排序
关键:两种操作
(1)、heapinsert向上操作。
(2)、heapify向下操作。
来源:CSDN
作者:对不起该昵称已存在
链接:https://blog.csdn.net/qq_43326818/article/details/104678389