Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.6k views
in Technique[技术] by (71.8m points)

arrays - Combining two given sequences into a new increasing sequence

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is wrong to search for the minimum value in the range of 1 to n+m-1 regardless of the value i. This may move the minimum value to the latter part of the array.

The line

        for (int j = 1; j < (n+m); j++)

should be

        for (int j = i + 1; j < (n+m); j++)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...