How to change the smallest value of a vector with the highest value?

0

For the moment I can only find the smallest and largest, but I can not change the 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;
    }
}
    
asked by anonymous 05.05.2018 / 02:24

2 answers

0

There are several ways to resolve this problem. The one I particularly find most efficient is to store the indexes (position in the vector) of the largest and smallest element of the vector, since it minimizes the amount of access to memory, and then using them to change 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;
}
    
05.05.2018 / 05:09
0

You must save the largest and smallest number separately and only after closing the key of the loop you exchange the two variables (major and minor). Besides that you have to also save the indexes, not just your 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;
    
05.05.2018 / 02:55