Problem with vector ordering in C

-1

I'm trying to make this problem, but the result always goes awry.

  

"Make a program that creates a 10-position vector filled by the user. Scan the vector and whenever the value of the i-position of the vector is less than the value of the i + 1 position you must change them. "

#include <stdio.h>

int main()
{

    int i,vet[10],aux;
    aux = 0;

    for(i=0;i<10;i++)
    {
        printf("Digite um valor:\n");
        scanf("%d",&vet[i]);
    }

    for(i=0;i<9;i++)
    {

        if(vet[i]<vet[i+1])
        {   

            aux = vet[i];
            vet[i] = vet[i+1];
            vet[i+1] = aux;


        }   
    }


    printf("\n");
    for(i=0;i<10;i++)
    {
        printf("%d\n",vet[i]);

    }

return 0;
}
    
asked by anonymous 29.11.2018 / 23:24

2 answers

0

Are you trying to sort using the correct bubble method? , so would the program (in ascending order):

but before the summary about ordination: Example: a = 10 b = 5, I can not change their values to order simply by saying that a = b or b = a since I lose the values, so I need an auxiliary to store the value to be changed. If I were to put it in ascending order:

1-I will change the value of b that will pass to

auxiliary = b b = a a = auxiliary

result: a = 5 b = 10

* watch for variable names so you do not have problems up front ^^

#include <stdio.h>

int main()
{
    int i;
    int j;
    int valor[10];
    int auxiliar;

    for(i=0; i<10; i++)
    {
        printf("Digite um valor:\n");
        scanf("%d",&valor[i]);
    }
    for(i=0; i<10; i++)
    {
        for(j=i+1; j<10; j++)
        {
            if(valor[i]>valor[j])
            { 
                auxiliar=valor[i];
                valor[i]=valor[j];
                valor[j]=auxiliar;
            }
        }
    }

    printf("\n");
    for(i=0; i<10; i++)
    {
        printf("%d\n",valor[i]);
    }
    return 0;
}
    
30.11.2018 / 00:42
0

Another way to do this is to use the XOR Swap algorithm where you can perform a value change without the use of an auxiliary variable.

int main() 
{

    int i, vet[10], aux;
    aux = 0;

    for (i = 0; i < 10; i++)
    {
        printf("Digite um valor:\n");
        scanf_s("%d", &vet[i]);
    }

    for (i = 0; i < 10; i++)
    {
        if (vet[i] < vet[i + 1])
        {
            // Operação SWAP XOR
            vet[i] ^= vet[i + 1];
            vet[i + 1] ^= vet[i];
            vet[i] ^= vet[i + 1];
        }
    }

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

    return 0;
}

If you want to know a little more, you have a reference here / a>

    
30.11.2018 / 12:26