Vector ordering

Asked

Viewed 337 times

0

I’m learning about vectors and matrices, and I haven’t been able to solve a question in the right way for a long time.

The statement says: Given some vector, sort it in sequential (numerical).

Example:

Entrada:{1,2,2,3,3,4}

Saída:{1,2,3,4,2,3}

I made a code that should take any given vector by the user, sort it in crescent shape and then re-sort in numerical sequential form. However, the problem is that my code always misses in the first sequence, leaving the largest number at the end of the vector and not in its proper 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
  • It explains better what it is to order increasing and sequential. This doesn’t make sense to me. I can’t imagine what this is for ReOrdenar().

  • Ascending ordernar: Leaves the values inside the ascending order vector. 1,2,3,4,5 or 1,2,3,3,3,4,5 or 1,2,3,3,4,5 Sort Sequential: Leaves the values in sequence from the smallest to the largest (No repetition followed). 1,2,3,4,1,2,3,1,2,1 or 1,2,3,4,5,2,3,4,5 or 1,2,3,4,2,3 .

No answers

Browser other questions tagged

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