Beim Einfügesortieren wächst der sortierte Teil links mit jedem neuen Wert. Schiebe größere Werte um eine Stelle nach rechts und lege den nächsten Wert in die Lücke. Ist alles schon sortiert, beträgt der Zeitaufwand Θ(n). Bei zufälliger Reihenfolge beträgt er im Mittel Θ(n²). Die umgekehrte Reihenfolge ist der schlechteste Fall und benötigt ebenfalls quadratische Zeit.
Ein einfaches Beispiel
Vor 3 ein 1 einfügen, dann 3 wieder verschieben, um 2 einzufügen. Drucke die sortierten Werte.
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Anzeigen
Das Beispiel Schritt für Schritt
Beginne mit [15, 3, 12, 6, -9, 9, 0].
Beginne mit dem sortierten Vorrang 15. Speichere den nächsten Wert, 3.
Schiebe 15 um eine Stelle nach rechts und setze 3 an den Anfang. Der sortierte Abschnitt lautet jetzt [3, 15].
Für jeden verbleibenden Wert verschiebe nur größere Werte vor der Einfügung. Gleichwertige Werte behalten ihre ursprüngliche Reihenfolge.
Insertionsort in PHP mit Erklärung
Quellcode in 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);
Ausgabe
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15