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;
}
You want to sort the vector?
– user28595
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}
– SnSilva
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
– user28595