2
Good evening. I started to study data structure in support of the book Data Structure and Algorithms 2nd ed (SZWARCFITER/MARKENZON). The first algorithm of the book deals with reversing the elements of the sequence in the vector, exchanging the position of the last element with the first, successively until the last element. The algorithm is this:
algoritmo 1.1: Inversão de uma sequencia
para i <- 1...[n/2] faça
temp <- S[i]
S[i] <- S[n - i + 1]
S[n -i + 1] <- temp
I wrote the algorithm on Portugol and added an excerpt that completes the list.
var
S:VETOR[1..10] de INTEIRO
i,j,temp,t: INTEIRO
inicio
para i de 1 ate 10 faca
S[i] <- i
fimpara
para i de 1 ate 10 faca
escreva(S[i], " ")
fimpara
Escreval(" ")
para j de 1 ate 10 faca
temp <- S[j]
S[j] <- S[10-j+1]
t <- S[10-j+1]
se (j>5) entao
S[j] <- -j+i
t <- -j+i
fimse
escreva(t, " ")
fimpara
fimalgoritmo
My question is about the variable i. Why does it assume the value 11 after printing the list? Before arriving at this code, I used an auxiliary variable k, to list the numbers smaller than 6 in reverse order, but I realized that i assumed the value 11, so I started doing -j+i. Somebody explain this to me?
From what little I know of algorithms, your vector should not start at "0" ?
– MagicHat
Yes, it starts from 0. S[1] = zero position of vector S.
– Felipe Maia