0

Why is the arrays being sorted?

I'm studying sort algorithms and this code bellow is sorting the array called "vector", but the method used to sort is a void method, why is the array being sorted without passing the pointer of "vector". I Thought that variables wouldn't being touched by void methods (unless you pass a pointer)

#include <iostream>
#include <stdlib.h>
#include <string>
#define TAM 10

using namespace std;

void imprimeVetor(int vetor[]) {
    int i;
    cout << "\n";
    for (i = 0; i < TAM; i++) {
        cout << " |" << vetor[i] << "| ";
    }
}

void insertion_sort(int vetor[TAM]) {

    int i, j, atual;

    for (i = 1; i < TAM; i++) {

        //Elemento atual em análise
        atual = vetor[i];

        //Elemento anterior ao analisado
        j = i - 1;

        //Analisando membros anteriores
        while ((j >= 0) && (atual < vetor[j])) {

            //Posiciona os elmeentos uma posição para frente
            vetor[j + 1] = vetor[j];

            //Faz o j andar para trás
            j = j - 1;

        }

        //Agora que o espaço foi aberto, colocamos o atual (Menor número) na posição correta
        vetor[j + 1] = atual;

    }

}

int main() {

    int vetor[TAM] = { 10,9,8,7,6,5,4,3,2,1 };

    insertion_sort(vetor);

    imprimeVetor(vetor);

    return 0;
}```
Davis Herring
  • 36,443
  • 4
  • 48
  • 76
  • 1
    Try to learn a bit more C++. You still use "C" style arrays, it is much more common nowadays (well since C++98 actually) to use `std::vector`. And for the record by passing the int[] you do pass a pointer to the array, so it can be changed. – Pepijn Kramer Jun 04 '23 at 14:43
  • By the rules of C++ in this code `void insertion_sort(int vetor[TAM]) {` the parameter `vetor` is a pointer. It might look like an array but it is not, it is impossible to have an array as a parameter in C++. – john Jun 04 '23 at 16:05
  • vetor[i] is dereferencing a pointer. By definition the same as *(vetor + i) and there's your pointer clear in the open. – gnasher729 Jun 04 '23 at 16:15
  • Re: “void method” — I don’t understand why this term seems to have become important to people. It’s just shorthand for “method that returns `void`”. There’s nothing special about that. The **only** difference between `void f() { /* do something */ return; }` and `int f() { /* do something */ return 42; }` is that the first one doesn’t return a value and the second one does. Other than that, there is **no difference** in what the two functions can and can’t do. – Pete Becker Jun 04 '23 at 20:47

0 Answers0