A ordenação por inserção faz crescer a parte ordenada à esquerda, um valor de cada vez. Desloca os valores maiores uma posição para a direita e coloca o valor seguinte no espaço livre. Se os dados já estiverem ordenados, o tempo é Θ(n). Em ordem aleatória, o tempo médio é Θ(n²). A ordem inversa é o pior caso e também exige tempo quadrático.
Exemplo simples
Inserir 1 antes 3, em seguida, deslizar 3 de lado novamente para inserir 2. Imprime os valores ordenados.
Início3 1 2
Resultado1 2 3
lesson.py
values = [3, 1, 2]
i = 1
while i < 3:
key = values[i]
j = i - 1
while j >= 0 and values[j] > key:
values[j + 1] = values[j]
j -= 1
values[j + 1] = key
i += 1
i = 0
while i < 3:
print(values[i])
i += 1
Saída
1
2
3
Exemplos do dia a dia
Inserir uma nova senha
Um funcionário mantém os bilhetes 2, 5 e 8 em ordem. Para onde deve ir o bilhete 6?
Início2 5 8 +6
Resultado2 5 6 8
Deslize 8 à direita. O local aberto após o 5 é a posição de inserção.
Acrescentar uma marcação de manhã
O seu diário começa às 10 e 12. Adicione uma consulta às 9.
Início10 12 +9
Resultado9 10 12
Ambos os compromissos posteriores mudam uma posição para abrir espaço.
Acrescentar um pagamento recebido mais tarde
Um livro de contas está ordenado por data e termina com os dias 4 e 6. Chega um pagamento do dia 7. Que entradas precisam de mudar de lugar?
Início4 6 +7
Resultado4 6 7
O último dia existente já precede 7. Anexá- lo sem alterar os outros itens.
Custo e limites
A ordenação por inserção funciona bem em listas curtas ou quase ordenadas. Uma lista por ordem inversa exige O(n²) deslocações e comparações.
Complexidade temporal
Melhor caso: Θ(n)
Caso médio: Θ(n²)
Pior caso: Θ(n²)
Ordenação por inserção em Python
Código-fonte em Python
class InsertionSortExample:
def __init__(self):
pass
def insertionSort(self, arr):
for i in range(len(arr)):
temp = arr[i]
holePosition = i
while(holePosition > 0 and arr[holePosition - 1] > temp):
arr[holePosition] = arr[holePosition - 1]
holePosition -= 1
arr[holePosition] = temp
return arr
def printArray(self, arr):
string = " ".join([str(item) for item in arr]);
print(string)
obj = InsertionSortExample()
arr = [15, 3, 12, 6, -9, 9, 0]
print("Before Sorting: ")
obj.printArray(arr)
result = obj.insertionSort(arr)
print("After Sorting: ")
obj.printArray(result)
Saída
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Anúncios
Acompanhe o exemplo passo a passo
Comece com [15, 3, 12, 6, -9, 9, 0].
Comece com 15 como o prefixo ordenado. Salve o próximo valor, 3.
Desloque 15 um lugar para a direita e insira 3 no início. O prefixo é agora [3, 15].
Para cada valor restante, deslocar apenas valores maiores antes de inseri-lo. Valores iguais mantêm a ordem original.
Ordenação por inserção em Python, passo a passo
Código-fonte em Python
class InsertionSortExample:
def __init__(self):
pass
def insertionSort(self, arr):
# Un-sorted array from position 1 to length -1
for i in range(len(arr)):
# Take the left most item in an un-sorted array to temp variable
temp = arr[i]
# Mark the left most position as empty or hole
holePosition = i
# Traverse the sorted array from right to left direction
# Move the item from the sorted array to the empty position (i.e. holePosition) only if the temp variable is less then
# Mark the current item's position as empty by decrementing the value by one
while(holePosition > 0 and arr[holePosition - 1] > temp):
arr[holePosition] = arr[holePosition - 1]
holePosition -= 1
# Once the comparison done, move the value in temp variable to the lastly marked empty position
arr[holePosition] = temp
# Return the sorted array
return arr
def printArray(self, arr):
# Loop the item and print each item in the console with white space seperated
string = " ".join([str(item) for item in arr]);
print(string)
obj = InsertionSortExample()
arr = [15, 3, 12, 6, -9, 9, 0]
print("Before Sorting: ")
obj.printArray(arr)
result = obj.insertionSort(arr)
print("After Sorting: ")
obj.printArray(result)
Saída
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15