Sort algorithm does not work

3

There is something missing in the program. It checks the order with a single number or a single time.

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

  /*4)escrever 10 números e ordenar em forma crescente e decrescente*/

int main()
{
    int opc;
    int numA=0, numB=0, numC=0, soma, aux=0, i;
    int vet[10];
    float media;

    printf("escolha qual exercicio quer executar:\n1)Ex1\n2)Ex2\n3)Ex3\n4)Ex4\n");
    scanf("%i", &opc);

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

    switch(opc)
    {
    case 4:

        printf("digite 10 numeros aleatorios:\n");

        /*inicio da fase de processamento*/
        for(i=0; i<10; i++)
        {
            scanf("%i", &vet[i]);
        }


    for(i=0; i<10; i++)/*crescente*/
    {
        if(vet[i]>vet[i+1])
        {
            aux=vet[i];
            vet[i]=vet[i+1];
            vet[i+1]=aux;
        }

        printf("%i", vet[i]);
    }

        /*fim da fase de processamento*/

        break;

    default:
        break;
    }

    return 0;
}
    
asked by anonymous 15.04.2015 / 00:27

1 answer

4

In the way you are doing, you only trade between two elements, but you do not continue to trade between all the elements. There are several ways to solve this. To compare all elements in a simple way you have to make two links to compare each element with all the others.

#include <stdio.h>

int main(void) {
    int vet[10];
    int aux;
    for(int i = 0; i < 10; i++) {
        scanf("%i", &vet[i]);
    }

    for(int i = 0; i < 10; i++) {
        for (int j = i + 1; j < 10; j++) { 
            if(vet[i] > vet[j]) {
                aux = vet[i];
                vet[i] = vet[j];
                vet[j] = aux;
            }
        }
        printf("%i", vet[i]);
    }
    return 0;
}

See running on ideone .

    
15.04.2015 / 00:37