Vector ordering
I'm learning about vectors and matrices, and I haven't been able to solve a question in the right way for quite some time.
The statement says: given some vector, order it in sequential(numerical) form.
Example:
Entrada:{1,2,2,3,3,4}
Saída:{1,2,3,4,2,3}
I made a code that should take any vector given by the user, sort it in ascending form and then re-sort in numerical sequential form. However, the problem is that my code always errors in the first sequence, leaving the higher number at the end of the vector and not in its due place (at the end of the first sequence).
Examples:
Entrada:{1,2,2,3,3,4}
Saída:{1,2,3,2,3,**4**}
Entrada:{1,2,5,2,5,3,3,4}
Saída:{1,2,3,2,3,4,5,**5**}
vetor = {}
tamanho = #vetor
function CriarVetor ()
print("Insira o tamanho do vetor")
tamanho = io.read("*number")
print("Insira os valores do vetor(ordenados ou nao)")
for i=1,tamanho do
vetor[i] = io.read("*number")
end
end
function Ordenar ()
for j=1,tamanho-1 do
for k=j+1, tamanho do
if vetor[j] > vetor[k] then
vetor[j],vetor[k] = vetor[k],vetor[j]
end
end
end
end
function ReOrdenar ()
for j=1,tamanho-1 do
if vetor[j] < vetor[j+1] and vetor[j] == vetor[j-1] then
vetor[j],vetor[j+1] = vetor[j+1],vetor[j]
end
end
end
CriarVetor()
Ordenar()
ReOrdenar()
for b=1, tamanho do
print("A posicao "..b.." do vetor vale: "..vetor[b])
end
0