major/minor in vectors

Asked

Viewed 879 times

3

I made some modifications to my code, it is in modifications at the end of the post I will modify it when I find it necessary.

hello, I am doing a college exercise, it is very simple, however, I am having some difficulty in it, the exercise asks to write two vectors of 5 possible and print a resulting vector ordering the elements in descending order (elements are of the type int), below the code:

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

int main()
{
    int vet1[5], vet2[5], rvet[10];
    int i, j, k, n1=0, n2=0;


    for(i=0; i<=4; i++)//Lê o vet1
    {

        printf("Digite para posicao %d do vet1:\n", n1++);
        scanf("%i", &vet1[i]);
    }

    printf("Obrigado, agora:\n");

    for(j=0; j<=4; j++)//Lê vet2
    {
        printf("Digite para posicao %d do vet2:\n", n2++);
        scanf("%d", &vet2[j]);

    }

    i=0;
    j=0;
    for(k=0;k<=9;k++)//Ordena os vetores
    {
        rvet[k]=i>j ? vet1[i++] : vet2[j++];

            printf("vet[%d]:%d\n", k, rvet[k]);
    }

    return 0;
}

my greatest difficulty is in for line 28(or the 3rd for), I can’t think of a better algorithm, so I posted an impression that aligns the vet2 first and then the vet1. I was thinking of making it smaller and bigger but when I modify the algorithm it always loses the data saved in vector 1 and 2 and then appears other random numbers. if anyone can help me thank you... my program has no errors and neither Warning tested in code::Locks and dev C++

MODIFICATIONS:

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

int main()
{
    int vet1[5], vet2[5], rvet[10];
    int i, j, k, x, y, n1=0, n2=0, aux=0;


    for(i=0; i<=4; i++)//Lê o vet1
    {

        printf("Digite para posicao %d do vet1:\n", n1++);
        scanf("%i", &vet1[i]);
    }


    fflush(stdin);
    system("cls");
    printf("Obrigado, agora:\n");

    for(j=0; j<=4; j++)//Lê vet2
    {
        printf("Digite para posicao %d do vet2:\n", n2++);
        scanf("%d", &vet2[j]);

    }

    fflush(stdin);
    system("cls");


    for(k=0; k<=4; k++)//preenche as 5 primeiras possições com vet1;
    {
            rvet[k]=vet1[i++];
    }

    for(k=5; k<=9; k++)
    {
        rvet[k]=vet2[j++];
    }   


    for(y=0; y<=9; y++)//coloca em ordem decrescente
    {
        for(k=x+1; k<=9; k++)
        {
            if(rvet[k]<rvet[x])
            {
                aux=rvet[x];
                rvet[x]=rvet[y];
                rvet[y]=aux;
            }
        }
    }

    for(k=0; k<=9; k++)
    {
        printf("%d->%d\n", k, rvet[k]);
    }

    return 0;
}

here they print first the vet1 and then the vet2.

2 answers

2


For this, I believe that the most efficient way would be to create a third vector with size 10, insert the values of the previous 2 vectors in this third, and then perform the ordering.

For that reason:

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

int main()
{
int vet1[5], vet2[5], rvet[10], n1=0, n2=0, aux=0;

for(int i=0; i<=4; i++) //Lê o vet1
{

    printf("Digite para posicao %d do vet1:\n", n1++);
    scanf("%i", &vet1[i]);
}

printf("Obrigado, agora:\n");

for(int j=0; j<=4; j++)//Lê vet2
{
    printf("Digite para posicao %d do vet2:\n", n2++);
    scanf("%d", &vet2[j]);

}

//intercalando os vetores aqui
for(int k=0; k<=4; k++)
{
rvet[k] = vet1[k]; //preenche as primeiras 5 posições
}

for(int k=5; k<=9; k++)
{
rvet[k] = vet2[k-5]; //preenche as próximas 5.
}

//Ordenação bubble sort
 for(int x = 0; x <= 9; x++ )
 {
   for(int y = x + 1; y <= 9; y++ ) // sempre 1 elemento à frente
    {
     // se o x for menor que a próxima posição do vetor, o x passa pra frente (ordem decrescente)
     if (rvet[x] < rvet[y] )
     {
      aux = rvet[x];
      rvet[x] = rvet[y];
      rvet[y] = aux;
     }
    }
  } // fim da ordenação
printf("*** VETOR ORDENADO ***\n");

for(int i=0; i<=9; i++)
{
  printf("%d\n", rvet[i]);
}

return 0;
}

Tip: When using a variable only to scroll through for, declare it in this way for(int var=0; var<=x; var++). Thus, when the loop ends, the variable ceases to exist, that is, it is not necessary to assign 0 to it.

@Leonardov.Degasperin in the last changes made I noticed the following errors in your code:

1 - The vectors vet1 and vet2 were filled in the indexes: 0, 1, 2, 3 and 4 (5 indexes, remembering that 0 also counts). You zeroed out the variables i and j, and then started going through the vector like this: vet1[i++], remembering that if i start with 0, i++ will automatically be 1, ignoring the index 0. This way, you go through the indexes: 1, 2, 3, 4 and 5, and in the index 5 there is nothing. Look at the code I posted above in the part that I insert the vectors and you’ll notice the difference.

2 - After you fill the vector rvet[] do not just make an if to order it. From here, forget the vectors vet1[] and vet2[]. To sort and display in descending order, it is necessary to traverse the entire array rvet[] and organize the numbers that are inside it, and something that helps in this task is an algorithm called sorting algorithm. Without the use of this algorithm, it is difficult to sort. What I used in my code (and I believe it is the simplest to understand) is the Bubble Sort, but then recommend you research on others too, it’s interesting.

Here you can consult what I used to make this ordination..

3 - Finally, to print the whole array ordered at once, it is necessary to create another for, as stated in the above code.

Any questions, do not hesitate to ask. Hug!

  • hmm I will see, only making an addendum after j=0; no need to declare rvet[10] because it has already been declared, but thanks if it works I will mark your answer =) otherwise I will add another comment talking about the mistakes that happens thanks.

  • @Vitor, your program intercalates, but does not order the vector as the OP requested.

  • @Kyllopardium Thanks for the observation, I’ve changed.

  • @kyllopardium I made some changes in the post I put modification under it a new code but with problem I’m still having complications with it in case either of the two can help me, the concise problem still in if the elements of the vetX are bigger q the elements of the vetY will print the vetorX first in its order and then idem with the vetY

  • @Victoralencarsantos comment the above read if you can =) thanks

  • @Leonardov.Degasperin consult the answer, I changed some things

  • @Leonardov.Degasperin, look at the line I put in the comment and make the change I suggested there.

  • then @Victoralencarsantos I made here ta equal your pore it prints the vet1 in the order of the vet1 and then the vet2 in the order of the vet2, and does not order the numbers, but thank you I will post the new code in the area notifications of my post if you want to take a look

  • @Leonardov.Degasperin friend, your edited code is still incorrect. Try to copy all the code I posted above and paste into your application and run.

  • @Victoralencarsantos when I compiled I got a scare had 14 errors, but it was the statements of the variables of the loop for I modified the statement and it worked, thank you I will study the code you made and try to make one alone

  • @Leonardov.Degasperin For nothing! Some compilers like Dev C++ aren’t as 'friendly' with variables declared within loops, but it’s great practice for cases like this, as it saves memory space.

  • @Victoralencarsantos that part I did not mean very well aux = rvet[x];&#xA; rvet[x] = rvet[y];&#xA; rvet[y] = aux;

  • @Leonardov.Degasperin chat won’t work for me, so: This is where we organize the numbers inside the array. If the value contained in the current position (rvet[x]) is less than the value in the next position (rvet[y]), the higher value goes up. This code snippet is only showing that if the higher number is coming later, it comes first. this article has a very clear explanation of this.

  • 1
  • @Victoralencarsantos thank you very much

Show 10 more comments

1

You didn’t do anything with the i and with the j in your last go and notice that even if you were what I believe you were thinking of doing would be wrong:

v1 : {2,5,20}  v2: {44,34,23}
v1[i]>v2[j]  => vres = [v2[j++]] 

the problem is that since the vectors v1 and v2 are not sorted, they will have unexpected results mainly if the value of the memory garbage is still less than one of the values used.

Tips on the code:

Use #define to not have to write the values everywhere (it is much easier to modify later).

order after concatenating the two vectors.

#include <stdio.h>
#include <stdlib.h>
#define MAXVETOR 5
#define MAXRESULTADO MAXVETOR*2



void ordena(int* vetor , int tamanho){
int c,d,swap;
for (c = 0 ; c < ( tamanho - 1 ); c++)
  {
    for (d = c ; d < tamanho - c - 1; d++)
    {
      if (vetor[d] > vetor[d+1]) //Troque de > para < para alterar a forma de ordenação.
      {
        swap       = vetor[d];
        vetor[d]   = vetor[d+1];
        vetor[d+1] = swap;
      }
    }
  }
}
void imprime_vetor(int *vetor,int tamanho){
    int i=0;
    printf("[");
    for(;i<tamanho;i++){
        if(i==tamanho-1){
            printf("%d]",vetor[i]);
        }
        else{
            printf("%d,",vetor[i]);
        }
    }
}

int main()
{
    int vet1[MAXVETOR] = {1,4,28,34,2}, vet2[MAXVETOR]={99,23,6,3,7}, rvet[MAXRESULTADO];
    int i, j, k, n1=0, n2=0;

/*
    for(i=0; i<MAXVETOR; i++)//Lê o vet1
    {

        printf("Digite para posicao %d do vet1:\n", n1++);
        scanf("%i", &vet1[i]);
    }

    printf("Obrigado, agora:\n");

    for(j=0; j<MAXVETOR; j++)//Lê vet2
    {
        printf("Digite para posicao %d do vet2:\n", n2++);
        scanf("%d", &vet2[j]);

    }
*/
    i=0;
    j=0;
    for(k=0;k<MAXRESULTADO;k++)//Intercala os vetores
    {
        rvet[k] = vet1[k];
    }
    for(k=MAXVETOR;k<MAXRESULTADO;k++)//Intercala os vetores
    {
        rvet[k] = vet2[k-MAXVETOR];
    }
    ordena(rvet,MAXRESULTADO);
    imprime_vetor(rvet,MAXRESULTADO);
    return 0;
}

Browser other questions tagged

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