两个有序数组进行合并,即将两数组中第一个数进行比较,小的数移入temp数组中,再进行比较,直到一个数组为空,将另一个数组全部转移即可。temp数组中即为两个数组合并后的有序数列。
归并排序是将数组不断的二分直到两个1个数的有序数组为止,然后通过递归,将有序数组慢慢扩大,直到整个数组有序为止。
原理可以看这个网址:https://visualgo-translation.club/zh/sorting
个人理解递归可以看作找mid(mid为有序数组的中间序号),mid的位置即是分为两个有序数组的位置。
#include<stdio.h>
//归并排序,从小到大//
/a数组分成first-mid,mid+1-last两份,进行合并//
#define N 10
void merge(int a[],int first,int mid,int last,int temp[])
{
int i=0,j=0;
int k=0;
i=first;
j=mid+1;
while(i<=mid && j<=last)
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=mid)
temp[k++]=a[i++];
while(j<=last)
temp[k++]=a[j++];
for(i=0;i<k;i++)
{
a[first+i]=temp[i];
}
}
void recurse(int a[],int first,int last,int temp[])
{
int mid=0;
if(first<last)
{
mid=(first+last)/2;
recurse(a,first,mid,temp);
recurse(a,mid+1,last,temp);
merge(a,first,mid,last,temp);
}
}
int main(void)
{
int i=0,a[N]={0},temp[N]={0};
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
}
recurse(a,0,N-1,temp);
for(i=0;i<N;i++)
{
printf("%d",a[i]);
}
return 0;
}