一长串一样的数字
原因
判断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;
}