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

Asked

Viewed 1,083 times

0

I created a code that takes a certain number set by the user, and makes the separation of pairs and odd, until then I was able to do, my problem is to put the numbers in ascending order so that the code looked more visually at the time of printing, printing both pairs and odd. follows the code as this currently.

#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;
}

As I would like to leave the exit: Pairs : 2,4,6 Odd: 1,3,5 and so on. (no need to be side by side but if you have how to do would like to know how it is).

  • Search by sorting algorithms. There is plenty of material on the internet.

2 answers

4


It would take another function 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 on this site: https://www.onlinegdb.com/online_c_compiler

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

-1

To order the array you can use the qsort() more or less in the exemplified way. To change the order, desc or asc just change the order of the a - b for 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()

Browser other questions tagged

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