归并排序的C实现

两个有序数组进行合并,即将两数组中第一个数进行比较,小的数移入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;
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值