可以看出归并排序就是把俩个左右拍好的俩个数组和并起来,所以合并的前提是必须是俩数组都是拍好序的
如何把俩数组都排好序,哪就 需要分治的思想了
#include<bits/stdc++.h>
using namespace std;
void mergee(int a[],int L,int M,int R)
{
int L_s=M-L;
int R_s=R-M+1;
int L1[L_s];
int R1[R_s];
//1,fill in the left sub a;
for(int i=L;i<M;i++)
{
L1[i-L]=a[i];
}
//2,fill in the right sub a ;
for(int i=M;i<=R;i++)
{
R1[i-M]=a[i];
}
//for(int i=0;i<R_s;i++)
//cout<<R1[i]<<endl;
//3.mergee into the a
int i=0,j=0,k=L;
while(i<L_s&&j<R_s)
{
if(L1[i]<R1[j])
{
a[k]=L1[i];
i++;
k++;
}
else
{
a[k]=R1[j];
j++;
k++;
}
}
while(i<L_s)
{
a[k]=L1[i];
i++;
k++;
}
while(j<R_s)
{
a[k]=R1[j];
j++;
k++;
}
}
int main()
{
int a[]={2,8,9,10,4,5,6,7};//这是对于俩段已经排好序的数组
int L=0;
int R=7;
int M=4;
mergee(a,L,M,R);
for(int i=0;i<=R;i++)
{
cout<<a[i]<<endl;
}
return 0;
}
#include<bits/stdc++.h>
using namespace std;
void mergee(int a[],int L,int M,int R)//合并
{
int L_s=M-L;
int R_s=R-M+1;
int L1[L_s];
int R1[R_s];
//1,fill in the left sub a;
for(int i=L;i<M;i++)
{
L1[i-L]=a[i];
}
//2,fill in the right sub a ;
for(int i=M;i<=R;i++)
{
R1[i-M]=a[i];
}
//for(int i=0;i<R_s;i++)
//cout<<R1[i]<<endl;
//3.mergee into the a
int i=0,j=0,k=L;
while(i<L_s&&j<R_s)
{
if(L1[i]<R1[j])
{
a[k]=L1[i];
i++;
k++;
}
else
{
a[k]=R1[j];
j++;
k++;
}
}
while(i<L_s)
{
a[k]=L1[i];
i++;
k++;
}
while(j<R_s)
{
a[k]=R1[j];
j++;
k++;
}
}
void mergesort(int a[],int L,int R)//分治
{
if(L==R)
{
return ;
}
else
{
int M=(L+R)/2;
mergesort(a,L,M);
mergesort(a,M+1,R);
mergee(a,L,M+1,R);//对于这个是因为mergee中的M是取到M+1注意下
}
}
int main()
{
int a[]={6,8,9,10,4,5,2,7};
int L=0;
int R=7;
int M=4;
mergesort(a,L,R);
for(int i=0;i<=R;i++)
{
cout<<a[i]<<endl;
}
return 0;
}