【归并排序】【合并两个有序数组】

本文介绍了一个简单的归并排序实现过程,通过将两个已排序数组合并为一个有序数组的方法来演示归并排序的基本思想。代码中详细展示了如何进行数组的合并,并在主函数中给出了一组示例数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
#include<error.h>

#define ERROR	-22

static int merge(int *a, int m, int *b, int n, int *c)
{
	int i = 0, j = 0, k = 0;
	if(a==NULL||b==NULL||c==NULL){
		fprintf(stderr, "arr should not be NULL\n");
		return ERROR;
	}
	
	if(m==0||n==0){
		fprintf(stderr, "num should not be zero\n");
		return ERROR;
	}
	
	while(i<m&&j<n){
		if(a[i]<b[j]){
			c[k++] = a[i++];
		}else{
			c[k++] = b[j++];
		}
	}
	
	while(i<m){
		c[k++] = a[i++];
	}
	while(j<n){
		c[k++] = b[j++];
	}
	return 0;
}
int main()
{
	int a[] = {4,7, 9, 20};
	int b[] = {5, 6};
	int m = sizeof(a)/sizeof(a[0]);
	int n = sizeof(b)/sizeof(b[0]);
	int c[m+n];
	if(merge(a, m, b, n, c)<0){
		return ERROR;
	}
	int i = 0;
	for(i=0; i<m+n; i++){
		printf("%d\t", c[i]);
	}
	printf("\n");
	return 0;
}

归并排序,实际上就是一个先分后合在一起的思想

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值