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.
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 PHP, passo a passo
Código-fonte em PHP
<?php
class InsertionSortExample {
public function insertionSort(&$arr) {
// Un-sorted array from position 1 to length -1
for($i = 1; $i < sizeof($arr); $i++) {
// 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 && $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;
}
}
public function printArray(&$arr) {
// Loop the item and print each item in the console with white space seperated
for($i = 0; $i < sizeof($arr); $i++) {
echo($arr[$i] . " ");
}
echo("\n");
}
}
$obj = new InsertionSortExample();
$arr = array();
array_push($arr, 15, 3, 12, 6, -9, 9, 0);
echo("Before Sorting: ");
$obj->printArray($arr);
$obj->insertionSort($arr);
echo("After Sorting: ");
$obj->printArray($arr);
Saída
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15