How to read two vectors and place the values in a third vector and in ascending order?

Asked

Viewed 38 times

-1

the statement of the problem is as follows: Make a program that reads an integer value N. After that, read N integer values by placing them in an A vector of size N. Then read an integer value M. Then read M integer values by placing-the in a vector B of size M. Assume that A and B will always be ordered crescently.

The program must join the values of A and B into a vector C so that C is also ordered. At the end, write the resulting vector C. Sorting algorithm not allowed.

I made the following code:

#include<stdio.h>
#include<stdlib.h>

int main(){
  int N;
  scanf("%d", &N);

  int vetorA[N];
  for(int i = 0; i < N; i++){
    scanf("%d", &vetorA[i]);
  }

  int M;
  scanf("%d", &M);

  int vetorB[M];
  for(int j = 0; j < M; j++){
    scanf("%d", &vetorB[j]);
  }

  int *vetorC;
  int j = 0;
  int k = 0;

  vetorC = (int *)(malloc(100 * sizeof(int)));

  if(vetorC == NULL){
    printf("\n erro ao alocar memoria");
    system("pause");
    exit(1);
  }

  for(int i = 0; i < (M + N); i++){
    if (vetorA[j] < vetorB[k]) {
      vetorC[i] = vetorA[j];
      j++;
    }
    else if(vetorB[k] < vetorA[j]){
      vetorC[i] = vetorB[k];
      k++;
    }

    else{
      vetorC[i] = vetorA[j];
      j++;
    }
  }
  for(int i = 0; i < (M + N); i++){
    printf("%d ", vetorC[i]);
  }
  
  free(vetorC);

}

but the program always goes wrong in the end. an example of input: 4 1 2 7 8 3 3 4 7 the output should be: 1 2 3 4 7 7 8 but my way out is: 1 2 3 4 7 7 0

1 answer

1


The error is that when j reaches the "M" value, all vector values have already been used, so vector A[j] is pointing to a random value, outside the matrix boundary.

The program could break, but for your misfortune did not break, and still caught a random value equal to a typed, which makes it seem that the problem is another.

The relevant part would be so, unless better judgment:

if (j >= N) {
  // vetorA esgotado
  vetorC[i] = vetorB[k];
  k++;
} else if (k >= M) {
  // vetorB esgotado
  vetorC[i] = vetorA[j];
  j++;
} else if (vetorA[j] <= vetorB[k]) {
  vetorC[i] = vetorA[j];
  j++;
} else if (vetorB[k] < vetorA[j]){
  vetorC[i] = vetorB[k];
  k++;
}

Note that I simplified the case of vector A[j] equal to vector B[j].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.