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.kt
fun main() {
var values = intArrayOf(3, 1, 2)
var i = 1
while (i < 3) {
var key = values[i]
var j = i - 1
while ((j >= 0) && (values[j] > key)) {
values[j + 1] = values[j]
j -= 1
}
values[j + 1] = key
i += 1
}
i = 0
while (i < 3) {
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 Kotlin
Código-fonte em Kotlin
fun insertionSort(arr: IntArray) {
val lastIndex: Int = arr.size - 1
for (i in 1..lastIndex) {
val temp: Int = arr[i]
var holePosition: Int = i
while(holePosition > 0 && arr[holePosition - 1] > temp) {
arr[holePosition] = arr[holePosition - 1]
holePosition--
}
arr[holePosition] = temp
}
}
fun printArray(arr: IntArray) {
val lastIndex: Int = arr.size - 1;
for (i in 0..lastIndex) {
val num = arr[i]
print("$num ")
}
println("")
}
fun main(args: Array<String>) {
val arr: IntArray = intArrayOf(15, 3, 12, 6, -9, 9, 0);
print("Before Sorting: ")
printArray(arr)
insertionSort(arr)
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 Kotlin, passo a passo
Código-fonte em Kotlin
fun insertionSort(arr: IntArray) {
val lastIndex: Int = arr.size - 1
// Un-sorted array from position 1 to size -1
for (i in 1..lastIndex) {
// Take the left most item in an un-sorted array to temp variable
val temp: Int = arr[i]
// Mark the left most position as empty or hole
var holePosition: Int = 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 && 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
}
}
fun printArray(arr: IntArray) {
val lastIndex: Int = arr.size - 1;
// Loop the item and print each item in the console with white space seperated
for (i in 0..lastIndex) {
val num = arr[i]
print("$num ")
}
println("")
}
fun main(args: Array<String>) {
val arr: IntArray = intArrayOf(15, 3, 12, 6, -9, 9, 0);
print("Before Sorting: ")
printArray(arr)
insertionSort(arr)
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