Le tri par insertion construit une partie triée à gauche, une valeur après l’autre. Décalez les valeurs plus grandes d’une place vers la droite, puis glissez la nouvelle valeur dans l’espace libéré. Si tout est déjà trié, le temps est Θ(n). Pour des valeurs en ordre aléatoire, il est en moyenne de Θ(n²). L’ordre inverse donne le pire cas, lui aussi quadratique.
Exemple simple
Insère 1 avant 3, puis déplace 3 de côté pour insérer 2. Affiche les valeurs triées.
Au départ3 1 2
Résultat1 2 3
main.go
package main
import "fmt"
func main() {
values := []int{3, 1, 2}
i := 1
for i < 3 {
key := values[i]
j := i - 1
for (j >= 0) && (values[j] > key) {
values[j + 1] = values[j]
j -= 1
}
values[j + 1] = key
i += 1
}
i = 0
for i < 3 {
fmt.Println(values[i])
i += 1
}
}
Sortie
1
2
3
Exemples du quotidien
Classer un nouveau ticket
Un agent range les billets 2, 5 et 8 dans l'ordre. Où doit aller le billet 6 ?
Au départ2 5 8 +6
Résultat2 5 6 8
Diapositive 8 droite. L'espace libre après 5 est la position d'insertion.
Ajouter un rendez-vous le matin
Ton agenda commence à 10 et 12. Ajoute une réunion à 9.
Au départ10 12 +9
Résultat9 10 12
Les deux rendez-vous suivants déplacent une position pour laisser de la place.
Ajouter un paiement reçu en retard
Un registre trié se termine les jours 4 et 6. Un paiement pour le jour 7 arrive. Quel changement se produit ?
Au départ4 6 +7
Résultat4 6 7
La dernière journée existante vient avant 7. Ajoutez-la sans déplacer les autres entrées.
Coût et limites
Tri par insertion fonctionne bien sur des listes courtes ou presque triées. L'ordre inverse nécessite O(n²) déplacements et comparaisons.
Complexité en temps
Meilleur cas: Θ(n)
Cas moyen: Θ(n²)
Pire cas: Θ(n²)
Tri par insertion en Go
Code source en Go
package main
import (
"fmt"
"strconv"
)
func insertionSort(arr []int) {
for i := 0; i < len(arr); i++ {
var temp = arr[i]
var holePosition = i
for holePosition > 0 && arr[holePosition - 1] > temp {
arr[holePosition] = arr[holePosition - 1]
holePosition--
}
arr[holePosition] = temp
}
}
func printArray(arr []int) {
for i := 0; i < len(arr); i++ {
fmt.Print(strconv.Itoa(arr[i]) + " ")
}
fmt.Println("")
}
func main() {
var arr = []int { 15, 3, 12, 6, -9, 9, 0 }
fmt.Print("Before Sorting: ")
printArray(arr)
insertionSort(arr)
fmt.Print("After Sorting: ")
printArray(arr)
}
Sortie
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Publicités
Suivez l’exemple étape par étape
Commencez avec [15, 3, 12, 6, -9, 9, 0].
Commence avec 15 comme préfixe trié. Enregistre la valeur suivante, 3.
Déplace 15 d'un cran à la droite et insère 3 au début. Le préfixe est maintenant [3, 15].
Pour chaque valeur restante, déplacez uniquement les valeurs plus grandes avant d'insérer la valeur. Les valeurs égales conservent leur ordre d'origine.
Tri par insertion en Go, étape par étape
Code source en Go
package main
import (
"fmt"
"strconv"
)
func insertionSort(arr []int) {
// Un-sorted array from position 1 to length -1
for i := 1; i < len(arr); i++ {
// Take the left most item in an un-sorted array to temp variable
var temp = arr[i]
// Mark the left most position as empty or hole
var 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
for 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
}
}
func printArray(arr []int) {
// Loop the item and print each item in the console with white space seperated
for i := 0; i < len(arr); i++ {
fmt.Print(strconv.Itoa(arr[i]) + " ")
}
fmt.Println("")
}
func main() {
var arr = []int { 15, 3, 12, 6, -9, 9, 0 }
fmt.Print("Before Sorting: ")
printArray(arr)
insertionSort(arr)
fmt.Print("After Sorting: ")
printArray(arr)
}
Sortie
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15