Vector ordering

0

I'm learning about vectors and arrays, and for a long time I can not solve a question correctly.

The statement says: Given some vector, sort it sequentially (numeric).

Example:

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

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

I've made a code that should take any vector given by the user, sort it incrementally and then re-sort in numerical sequential form. However, the problem is that my code always errs 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
    
asked by anonymous 08.07.2016 / 18:38

0 answers