#include<stdio.h>
void merge(int arr[],int L,int M,int R)
{
int left_size=M-L;
int right_size=R-M+1;
int left_arr[left_size];
int right_arr[right_size];
int i,j,k;
//fill the left array
for(int i=L;i<M;i++)
{
left_arr[i-L]=arr[i];
}
//fill the right array
for(int i=M;i<=R;i++)
{
right_arr[i-M]=arr[i];
}
//merge into the original arr
i=0,j=0,k=L;
while(i<left_size && j<right_size)
{
if(left_arr[i]<right_arr[j])
{
arr[k]=left_arr[i];
i++;
k++;
}
else
{
arr[k]=right_arr[j];
j++;
k++;
}
}
while(i<left_size)
{
arr[k]=left_arr[i];
i++;
k++;
}
while(j<right_size)
{
arr[k]=right_arr[j];
j++;
k++;
}
}
void MergeSort(int arr[],int L,int R)
{
if(L==R)
{
return;
}
else
{
int M=(L+R)/2;
MergeSort(arr,L,M);
MergeSort(arr,M+1,R);
merge(arr,L,M+1,R);
}
}
int main()
{
int arr[]={7,3,10,-3,7,9,45,12,18,-5,0,-13,3,14,20,4,0,5,7,3};
int L=0;
int R=19;
MergeSort(arr,L,R);
for(int i=0;i<=R;i++)
{
printf("%d\n",arr[i]);
}
return 0;
}
代码讲解参考视频 https://www.bilibili.com/video/av9982752/?spm_id_from=333.788.videocard.0