c++problem: Selection Sort

Asked

Viewed 72 times

0

hi wanted a help to solve a problem of c++:

I am making a code and used Selection Sort but it is with a bug in the output results

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 someone could help me out

problem : insert 1,2,3,2,1

he comes out : 1,2,2,3,30

What do I do

1 answer

1

Hello, when you check whether the smallest element in the Vector[i.. TAM] sub-vector is the Vector[i] element itself, 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 aux variable the content that is in Vector[i], as if is without keys, every time you j increment in the internal loop, the following code is executed:

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

To correct 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;
}

Browser other questions tagged

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