#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;
}
归并排序,实际上就是一个先分后合在一起的思想