c ++ problem: selection sort

0

Hi, I wanted help solving a problem with c++ :

I am making a code and I used the selection sort but it has a bug in the results output

void select_sort (int vetor [TAM])
{
    int menor,aux;

    cout << "Digite as 5 posicoes, de maneira que preencha as posicoes do nosso vetor " << endl;
    cout << " "<< endl;
    for(int i = 0; i < TAM; i++)
    {
        menor = i;
        for(int j = i + 1; j < TAM; j++)
        {
            if(vetor[menor] > vetor[j])
                menor = j;

            if(i != menor)
                aux=vetor[i];
            vetor[i] = vetor[menor];
            vetor [menor] = aux;
        }
    }

    cout << " o vetor fica assim:" << endl;
    cout << " " << endl;

    for(int i = 0; i < TAM; i++)
    {

        cout << vetor[i] << " | ";
    }
    cout << " " << endl;
}

In case it is a function Can someone help me?

problem: I enter 1,2,3,2,1

it exits: 1,2,2,3,30

What I do

    
asked by anonymous 24.06.2017 / 18:00

1 answer

1
Hello, when you check if the smallest element in the Vector sub vector [i..TAM] is the Vector element itself [i], you are using the code:

if(i != menor)
  aux=vetor[i];
  vetor[i] = vetor[menor];
  vetor [menor] = aux;

Note that in this case you are only assigning to the variable the contents of Vector [i], as if there are no keys, every time you increment in the internal loop, the following code is executed:

vetor[i] = vetor[menor];
vetor [menor] = aux

To fix this, change:

if(i != menor)
    aux=vetor[i];
    vetor[i] = vetor[menor];
    vetor [menor] = aux;

To:

if(i != menor) {
   aux=vetor[i];
   vetor[i] = vetor[menor];
   vetor [menor] = aux;
}
    
24.06.2017 / 19:56