How to exchange the lowest value of a vector with the highest value?

Asked

Viewed 691 times

0

For now I can only find the smallest and largest, but I can’t change positions.

for(int i=0; i < vetor.length; i++){
    temp = vetor[i];


    if(maior < temp){
        maior  = vetor[i];
        vetor[i] = menor;
        menor = maior;
    }
     if(menor > temp){
        menor  = vetor[i];
        vetor[i] = maior;
        maior = menor;
    }
}
  • You want to sort the vector?

  • No, I need to invert the position of the lowest value with the highest. ex: {1,2,3,4,5,6,7,8,9} {9,2,3,4,5,6,7,8,1}

  • 1

    vector is already ordered? If already, you do not need any of that there, only change the first and the last. Edit the question and explain the scenario better, it is not clear

2 answers

0

You must save the largest and smallest number separately and only after closing the loop key you exchange the two variables (larger and smaller). In addition to which you have to save also the contents, not only their values.

    maior = vetor[0];
    menor = vetor[0];

    for(int i=0; i < vetor.length; i++){
        atual = vetor[i];

        if(atual > maior){
            indiceMaior  = i;
            maior = vetor[i];
        }
         if(atual < menor){
            indiceMenor  = i;
            menor = vetor[i];
        }
    }

    vetor[indiceMenor] = maior;
    vetor[indiceMaior] = menor;

0


There are several ways to solve this problem. The one that I find particularly efficient is stored the indexes (position in the vector) of the largest and smallest element of the vector, because thus minimizes the amount of accesses to memory, and then using them to exchange the values:

int main(){

    int indiceMaior, indiceMenor;
    int auxiliar;

    //inicializa os índices com 0
    indiceMaior = indiceMenor = 0;

    for(int i=1; i < vetor.length; i++){

        if(vetor[i] > vetor[indiceMaior]) indiceMaior = i;

        if(vetor[i] < vetor[indiceMenor]) indiceMenor = i;
    }

    //armazenamos o maior valor para não perder-lo, 
    //pois iremos sobreescrever com o menor valor
    auxiliar = vetor[indiceMaior];
    vetor[indiceMaior] = vetor[indiceMenor];
    vetor[indiceMenor] = auxiliar;
}
  • Thank you very much my friend!!!!!! It worked here

  • Good! You’re welcome. If this answer has solved your problem and/or helped you. Up Vote and select as answer accepted ( click on "v" );

Browser other questions tagged

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