日常编程笔记 | 2022.9.30 | 归并排序

一长串一样的数字

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

原因

判断ab元素大小的时候把== 写成=了呜呜呜、

输出极小数字

一看显然是数组下标越界
在这里插入图片描述
果然

在这里插入图片描述

这里没有相应在b的判断中写出ab元素相等的情况,则输出c未赋值前的数

c源代码

#include<stdio.h>
#include<stdlib.h> 
#include<time.h>
#define N 5

int* MergeSort(int*a,int asize, int*b,int bsize);

int main()
{
	//test the function of MergeSort
	int *a = (int*)malloc(sizeof(int)*N);
	int *b = (int*)malloc(sizeof(int)*N);
	int *c;
	int i;
	
	srand((unsigned int)time(0));//initialize the seed
	
	a[0] = rand()%50;//assign a random number from 0 to 9 to a[0] and b[0]
	b[0] = rand()%50;

	for(i = 1; i < N; i++)
	{
		a[i] = a[i - 1] + rand()%50;//to guarantee the array is in increasing order
		b[i] = b[i - 1] + rand()%50;	
	}
	c = MergeSort(a, N, b, N);
	
	for(i = 0; i < 2*N; i++)
	{
		printf("%d ", c[i]);
	}
	
	return 0;	
}

int* MergeSort(int*a, int asize, int*b, int bsize)
{

	int*c = (int*)malloc(sizeof(int)*(asize + bsize));//create a new array to store the sorted array

	int csize = asize + bsize;//the size of c
	
	int ai = 0, bi = 0, ci = 0;//ai for a index; bi for b index; ci for c index
	
	for(ci = 0; ci < csize; ci++)
	{
		if(ai < asize && ((a[ai] < b[bi]) || (a[ai] == b[bi])))//if a[ai] <= b[bi], then sort a[ai] into c[ci]
		{
			c[ci] = a[ai];
			ai++;
		}
		else if(bi < bsize && ((b[bi] < a[ai]) || (b[bi] == a[ai])))//if a[ai] > b[bi], then sort b[bi] into c[ci]
		{
			c[ci] = b[bi];
			bi++;
		}
	}
	
	return c;	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值