Invert array (vector) without an external function, 'manually'

Asked

Viewed 859 times

5

Friends, I always invert vectors using an auxiliary in an external function (I think the standard way), however until recently a friend told me that had a way to invert vectors without using an auxiliary, I asked to show me but ended up not showing me? I searched the net for something done in such a way and found nothing. How do I do that.

     aux = vetor[i+8];
     vetor[i+8] = vetor[i];
     vetor[i] = aux;
  • 2

    The use of auxiliary variable is the canonical form of exchanging the value of 2 variables. The other ways of doing this are "artificial". Continue to do with the auxiliary you do well (the compiler will optimize the code better than you can with "tricks").

  • pmg sorry I took this function only to demonstrate the use I make of the auxiliaries I will change it to make it clearer. I want to learn just for the sake of curiosity, it may be that I don’t even use it on the day - day-to-day, but what’s wrong

  • 1

    A common "trick" to swap the value of 2 variables without using an auxiliary variable is called XOR swap. See, for example, http://answall.com/questions/9497/howto work the algorithm-do-xor-swap

2 answers

6


The trick is in building the cycle for, must count from the end to the beginning of the array (vector)

#include <stdio.h>

int main() {

   int original[] = {1,2,3,4,5,6};
   int count = sizeof(original) / sizeof(int); // 6, numero de elementos no array original 
   int revertido[count], i, j; // declaramos que o array revertido vai ter o mesmo numero de elementos que original

   // vamos iniciar o i em count - 1, (5 indexes dos elementos do array original) vai servir para percorrermos o original do fim para o inicio, subtraimos 1 a cada volta
   // vamos iniciar o j em 0 para podermos armazenar cada valor do original a partir do index 0 no array revertido, j vai ser cada index do array revertido
   // o loop e finalizado quando j < count (quando j for 5), iria dar o mesmo resultado se a condicao fosse i >= 0

   for (i = count-1, j = 0; j < count; i--, j++) {
      revertido[j] = original[i]; // no primeiro loop o ultimo valor do original vai ser o primeiro valor (com index 0) do array revertido, no segundo loop o penultimo do original vai ser o segundo do revertido, etc...
   }

   for (i = 0; i < count; i++) {
      printf("%d \n", revertido[i]);
   }

   return (0);
}

Once understood the logic, if you want to simplify, you can solve using only the variable i in the loop, and so we don’t even need the j:

for ( i = 0; i < count; i++) {
   revertido[i] = original[count - i - 1];
}

// Se i for zero, count - i - 1 será o
// último elemento (original[6 - 0 - 1] = original[5]), se for 1, será o
// penúltimo, e assim sucessivamente.

2

Although your question is in C language, just as a contribution to your question, in C++ (Object Oriented) we can use a very useful method for this and abstract this complexity:

#include <vector>
#include <algorithm>

void main() {
  std::vector<int> vetor_xpto;
  //quando popular pode usar...
  std::reverse(vetor_xpto.begin(), vetor_xpto.end());
}
  • Not forgetting if the purpose is learning logic, my answer should not be considered :-)

Browser other questions tagged

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