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.c
#include <stdbool.h>
#include <stdio.h>
int main(void) {
int values[] = {3, 1, 2};
int i = 1;
while (i < 3) {
int key = values[i];
int 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) {
printf("%d\n", 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.
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 C, passo a passo
Código-fonte em C
#include<stdio.h>
void insertionSort(int arr[], size_t size) {
// Un-sorted array from position 1 to size -1
for(size_t i = 1; i < size; i++) {
// Take the left most item in an un-sorted array to temp variable
int temp = arr[i];
// Mark the left most position as empty or hole
int 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 && 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;
}
}
void printArray(const int arr[], size_t size) {
// Loop the item and print each item in the console with white space seperated
for(size_t i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main(int argc, const char * argv[]) {
int arr[] = { 15, 3, 12, 6, -9, 9, 0 };
const size_t SIZE = sizeof(arr) / sizeof(*arr);
printf("Before Sorting: ");
printArray(arr, SIZE);
insertionSort(arr, SIZE);
printf("After Sorting: ");
printArray(arr, SIZE);
return 0;
}
Saída
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15