I am doing the following problem:
Giving the sequence a
consisting of n
integer numbers and the sequence b
consisting of m
integer numbers, two sequences are arranged in increasing order. Combining two above sequences into a new sequence c
such that c
is also an increasing sequence. Printing c
.
Input:
3
1 3 4
4
1 2 3 5
Output:
1 1 2 3 3 4 5
My idea is first combining two sequences into sequence c
, then sorting sequence c
in increasing order. This is my code:
#include <stdio.h>
int main() {
//Inputting sequence a and b
int n, m;
int a[1001], b[1001];
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d", &b[i]);
}
//Combine two sequence into c
int c[1001];
for (int i = 0; i < n; i++) {
c[i] = a[i];
}
for (int i = 0; i < m; i++) {
c[i + n] = b[i];
}
//Arrange sequence c in increasing order
int mid;
for (int i = 0; i < (n + m - 1); i++) {
for (int j = 1; j < (n + m); j++) {
if (c[i] > c[j]) {
mid = c[i];
c[i] = c[j];
c[j] = mid;
}
}
}
//Printing c
for (int i = 0; i < (n + m); i++) {
printf("%d ", c[i]);
}
return 0;
}
However, when I test with the test case [1,2,4],[1,2,5]
, the result is 1 4 2 2 1 5
. Can anyone point out the error in my code? I truly appreciate that.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…