Você está na página 1de 49

Algoritmos de Ordenao

Dado um vetor v com N elementos, a ordenao consiste em organizar todos esses N elementos em uma ordem (no (no-crescente, no-decrescente etc) Exemplo:
v = {1, 9, 8, 5, 3, 7, 4}

Depois de ordenado de forma no no-decrescente, v fica: v = {1, 3, 4, 5, 7, 8, 9}

Insert Sort
Outros nomes:
Bubble sort Selection sort

Consite em posicionar o menor ou o maior elemento em seu lugar correto N vezes consecutivas

Insert Sort
for i=1,N do for j=i+1,N do if v[i]>v[j] then ]>v[j] v[i],v[j] = v[j],v[ ],v[j] v[j],v[i] end end end

Insert Sort
i

1985374
j

Insert Sort
i

1985374
j

Insert Sort
i

1985374
j

Insert Sort
i

1985374
j

Insert Sort
i

1985374
j

Insert Sort
i

1985374
j

Insert Sort
i

1985374
j

Insert Sort
i

1895374
j

Insert Sort
i

1598374
j

Insert Sort
i

1398574
j

Insert Sort
i

1398574
j

Insert Sort
i

1398574
j

Insert Sort
i

1389574
j

Insert Sort
i

1359874
j

Insert Sort
i

1359874
j

Insert Sort
i

1349875
j

Insert Sort
i

1348975
j

Insert Sort
i

1347985
j

Insert Sort
i

1345987
j

Insert Sort
i

1345897
j

Insert Sort
i

1345798
j

Insert Sort

1345789

Insert Sort

1345789
Nmero de operaes: (N-1) + (N-2) + (N-3) + + 3 + 2 + 1 3) N*(N-1) 1) 2

Insert Sort
Ideia:
Se o vetor j estiver ordenado em alguma interao, seria interessante detectar isso e parar o algoritmo.

Como detecto se um vetor est ordenado?


ordenado = true for i=1,N do if v[i]>v[i+1] then ordenado = false end end

Insert Sort ( (melhoria)


for i=N,2,-1 do trocas = false for j=1,i-1 do if v[j]>v[j+1] then v[j],v[j+1] = v[j+1],v[j] trocas = true end end if not trocas then break end end

Insert Sort ( (melhoria)


i

1985374
j

Insert Sort ( (melhoria)


i

1985374
j

Insert Sort ( (melhoria)


i

1895374
j

Insert Sort ( (melhoria)


i

1859374
j

Insert Sort ( (melhoria)


i

1853974
j

Insert Sort ( (melhoria)


i

1853794
j

Insert Sort ( (melhoria)


i

1853749
j

Insert Sort ( (melhoria)


i

1853749
j

Insert Sort ( (melhoria)


i

1583749
j

Insert Sort ( (melhoria)


i

1538749
j

Insert Sort ( (melhoria)


i

1537849
j

Insert Sort ( (melhoria)


i

1537489
j

Insert Sort ( (melhoria)


i

1537489
j

Insert Sort ( (melhoria)


i

1357489
j

Insert Sort ( (melhoria)


i

1357489
j

Insert Sort ( (melhoria)


i

1354789
j

Insert Sort ( (melhoria)


i

1354789
j

Insert Sort ( (melhoria)


i

1354789
j

Insert Sort ( (melhoria)


i

1345789
j

Insert Sort ( (melhoria)


i

1345789
j

Insert Sort ( (melhoria)

1345789

Você também pode gostar