Merge sort to take the idea of divide and conquer, respectively, each row from left and right halves, and constantly calls itself recursively until only the end of a recursive elements, began to backtrack, call the merge function to merge two ordered sequence, and then every time of the merger time to catch the end of a maximum int so afraid of the last number will not be sorted.
#include <bits/stdc++.h>
using namespace std;
void merge(int a[],int n,int left ,int mid,int right);
void merge_sort(int a[],int n,int left,int right);
const int Maxn=5e5;
const int Sentinel=0x3f3f3f3f;
int L[Maxn/2],R[Maxn/2];
int cnt;
int main()
{
int n;
int a[1000];
cin>>n;
for(int i=0;i<n;i++) cin>>a[i];
merge_sort(a,n,0,n);
for(int i=0;i<n;i++) cout<<a[i]<<' ';
}
void merge(int a[],int n,int left ,int mid,int right)
{
int n1=mid-left;
int n2=right-mid;
for(int i=0;i<n1;i++) L[i]=a[left+i];
for(int i=0;i<n2;i++) R[i]=a[mid+i];
L[n1]=R[n2]=Sentinel;
int i=0,j=0;
for(int k=left;k<right;k++)
{
cnt++;
if(L[i]<R[j]){
a[k]=L[i++];
}
else{
a[k]=R[j++];
}
}
}
void merge_sort(int a[],int n,int left,int right)
{
if(left<right)
{
int mid=(left+right)>>1;
merge_sort(a,n,left,mid);
merge_sort(a,n,mid+1,right);
merge(a,n,left,mid,right);
}
}
--------------------------------------------
above for the realization of the principle of aid the C ++ merge function can be simplified merge_sort () code.
#include <bits/stdc++.h>
using namespace std;
void merge_sort(int a[],int n,int left,int right);
const int Maxn=5e5;
int main()
{
int n;
int a[Maxn];
cin>>n;
for(int i=0;i<n;i++) cin>>a[i];
merge_sort(a,n,0,n);
for(int i=0;i<n;i++) cout<<a[i]<<' ';
}
void merge_sort(int a[],int n,int left,int right)
{
if(left<right)
{
int mid=(left+right)>>1;
merge_sort(a,n,left,mid);
merge_sort(a,n,mid+1,right);
merge(a+left,a+mid+1,a+mid+1,a+right,a+left);
}
}