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
main.go
package main
import "fmt"
func main() {
values := []int{3, 1, 2}
i := 1
for i < 3 {
key := values[i]
j := i - 1
for (j >= 0) && (values[j] > key) {
values[j + 1] = values[j]
j -= 1
}
values[j + 1] = key
i += 1
}
i = 0
for i < 3 {
fmt.Println(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 Go
Código-fonte em Go
package main
import (
"fmt"
"strconv"
)
func insertionSort(arr []int) {
for i := 0; i < len(arr); i++ {
var temp = arr[i]
var holePosition = i
for holePosition > 0 && arr[holePosition - 1] > temp {
arr[holePosition] = arr[holePosition - 1]
holePosition--
}
arr[holePosition] = temp
}
}
func printArray(arr []int) {
for i := 0; i < len(arr); i++ {
fmt.Print(strconv.Itoa(arr[i]) + " ")
}
fmt.Println("")
}
func main() {
var arr = []int { 15, 3, 12, 6, -9, 9, 0 }
fmt.Print("Before Sorting: ")
printArray(arr)
insertionSort(arr)
fmt.Print("After Sorting: ")
printArray(arr)
}
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 Go, passo a passo
Código-fonte em Go
package main
import (
"fmt"
"strconv"
)
func insertionSort(arr []int) {
// Un-sorted array from position 1 to length -1
for i := 1; i < len(arr); i++ {
// Take the left most item in an un-sorted array to temp variable
var temp = arr[i]
// Mark the left most position as empty or hole
var 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
for holePosition > 0 && arr[holePosition - 1] > temp {
arr[holePosition] = arr[holePosition - 1]
holePosition--
}
// Once the comparison done, move the value in temp variable to the lastly marked empty position
arr[holePosition] = temp
}
}
func printArray(arr []int) {
// Loop the item and print each item in the console with white space seperated
for i := 0; i < len(arr); i++ {
fmt.Print(strconv.Itoa(arr[i]) + " ")
}
fmt.Println("")
}
func main() {
var arr = []int { 15, 3, 12, 6, -9, 9, 0 }
fmt.Print("Before Sorting: ")
printArray(arr)
insertionSort(arr)
fmt.Print("After Sorting: ")
printArray(arr)
}
Saída
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15