//a1,a2 为递增序列.
int *mergeSortedArray(int *a1 , int a1len, int *a2, int a2len){
int len = a1len + a2len;
//分配空间,调用方free()空间
int *p = (int*)malloc(sizeof(int)*len);
//头尾比较,如果a1的尾比a2的头小,说明a1的所有数字都比a2小
if(a1[a1len - 1] <= a2[0]){
memcpy(p,a1,a1len * sizeof(int));
memcpy(p+a1len,a2,a2len * sizeof(int));
return p;
}
if(a1[0] >= a2[a2len -1]){
memcpy(p,a2,a2len * sizeof(int));
memcpy(p+a2len,a1,a1len * sizeof(int));
return p;
}
int j = 0,k = 0;
for(int i = 0;i < len;i++){
if(a1[j] <= a2[k] && j <= a1len - 1){
p[i] = a1[j];
j++;
} else {
p[i] = a2[k];
k++;
}
}
//打印
for( int i = 0;i < len ;i++){
printf("%d, ",p[i]);
}
printf("\n");
return p;
}
网友评论