//第一种方法:现将两个数组合并到第三个数组中,再对第三个数组排序(偷懒的方法)
/*
int a[] = {2, 20, 8, 30}, b[] = {5, 9, 13, 29}, c[8] = {0};
for (int i = 0; i < 4; i++) {
c[i] = a[i];
}
for (int i = 4, j = 0; i < 8; i++, j++) {
c[i] = b[j];
}
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7 -i; j++) {
if (c[j] > c[j + 1]) {
int temp = c[j];
c[j] = c[j + 1];
c[j + 1] = temp;
}
}
}
for (int i = 0; i < 8; i++) {
printf("%d ", c[i]);
}
*/
//标准方法第二种方法:边比较边存储(这才锻炼逻辑)
int a[4] = {2, 5, 8, 30}, b[4] = {5, 9, 13, 29}, c[8] = {0}, m = 0, n = 0, i = 0;//c[]存储a[]和b[]比较后的元素,m指向a[]的元素下标,n指向b[]的元素下标,i指向c[]的元素下标
while (m != 4 && n != 4) {//a[]且b[]都没有排完
if (a[m] < b[n]) {
c[i] = a[m];//把小数赋给c[i];
m++;//a[]的下标增1;
i++;//c[]的下标增1;
} else if (a[m] > b[n]) {
c[i] = b[n];//把小数赋给c[i];
n++;//b[]的下标增1;
i++;//c[]的下标增1;
} else {//若相等
c[i] = a[m];//先把a[m]赋给c[i]
c[++i] = b[n];//先讲i增1,再将b[n]赋给c[i]
m++;//a[]的下标增1;
n++;//b[]的下标增1;
i++;//c[]的下标增1;
}
}
if (m == 4) {//若a[]先排完
for (int j = n; j < 4; j++) {
c[4 + n] = b[j];//将b[]之后的元素逐个赋给c[]
}
}
if (n == 4) {//若b[]先排完
for (int j = m; j < 4; j++) {
c[4 + m] = a[j];//将a[]之后的元素逐个赋给c[]
}
}
printf("合并后的序列为:\n");
for (int j = 0; j < 8; j++) {
printf("%d ", c[j]);//打印c[]
}
printf("\n");