How is the logic to print the numbers in ascending order in C

0

I created a code that takes a certain number of numbers set by the user, and does the separation of odd and even, until I got to do it, my problem is to put the numbers in ascending order so that the code looks more beautiful visually at the time of the printing, printing in order both the odd and even. follow the code as it currently is.

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

int main() {

  int quantVetor = 0,vetPar[100],vetImpar[100],quantPar = 0,quantImpar = 0,posicao[100],i;

  printf("Digite o tamanho do vetor que deseja\n");
  scanf("%d",&quantVetor);
  //
  printf("Atribua os valores ao vetor\n");
  for (i = 0; i < quantVetor ; i++) {
    scanf("%d", &posicao[i]);

  if(posicao[i] % 2 == 0){
      vetPar[quantPar]=posicao[i];
      quantPar++;
} else{
      vetImpar[quantImpar]=posicao[i];
      quantImpar++;
} // fim else
  } // fim for

  printf("\n\n");

  for (i = 0; i < quantPar; i++) {
   printf("par %d\n\n",vetPar[i] );
  } // fim for
  for (int i = 0; i < quantImpar; i++) {
    printf("impar %d\n\n",vetImpar[i] );
  } // fim for
  return 0;
}

How I wish it were the output: Pairs: 2,4,6 Odds: and so on. (It does not have to be side by side but if you have to do it, I'd like to know how it is.)

    
asked by anonymous 17.10.2018 / 20:37

2 answers

4

Another function would be required to sort the values. I'll leave a simple example:

for (int indice = 0; indice < quantPar; indice++) //Loop para percorrer o vetor
{
        for (int indice2 = 0; indice2 < quantPar; indice2++) //Loop para comparar
        {
            if (vetPar[indice2] > vetPar[indice]) //Comparando os elementos
            {
                int tmp = vetPar[indice]; // Usando uma variável temporária para armazenar o valor
                // Trocando os valores
                vetPar[indice] = vetPar[indice2]; 
                vetPar[indice2] = tmp;
            }  
        }
    }

I tested this site: link

This implementation is known as Bubble Sort, but there are others. For example: Inserting Luck, Heap Sort, Selection sort and Quick sort. Link to a more complete list

    
17.10.2018 / 21:44
-1

To sort array you can use qsort() plus or minus as shown. To change the order, desc or asc , just change the comparison order from a - b to b - a

int compareInt(const void *a, const void *b) {
   return ( *(int*)a - *(int*)b );
}

int main() {
   /** le valores.. **/

   qsort(pares, tam_array_pares, sizeof(int), compareInt);
   qsort(impares, tam_array_impares, sizeof(int), compareInt);

   /** printa valores **/
} 

More details here: qsort ()

    
17.10.2018 / 21:02