Sortarea prin inserție formează în stânga o parte ordonată, adăugând câte o valoare. Mută valorile mai mari cu un loc la dreapta și pune valoarea următoare în spațiul liber. Dacă lista este deja sortată, timpul este Θ(n). Pentru o ordine aleatorie, timpul mediu este Θ(n²). Ordinea inversă este cazul cel mai nefavorabil și cere tot timp pătratic.
Exemplu simplu
Se introduce 1 înainte de 3, apoi aluneca 3 o parte din nou pentru a introduce 2. Printează valorile sortate.
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Anunțuri
Urmărește exemplul pas cu pas
Pornește de la [15, 3, 12, 6, -9, 9, 0].
Începe cu 15 ca prefixul sortate. Păstrează valoarea următoare, 3.
Mutaţi 15 un loc la dreapta şi introduceţi 3 la început. Prefixul este acum [3, 15].
Pentru fiecare valoare rămasă, se modifică numai valorile mai mari înainte de introducerea acesteia. Valorile egale păstrează ordinea lor originală.
Sortare prin inserție în PHP, pas cu pas
Cod sursă în 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);
Ieșire
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15