L’ordinamento per inserimento costruisce una parte ordinata a sinistra, un valore alla volta. Sposta i valori più grandi di un posto a destra e inserisce il nuovo valore nello spazio lasciato libero. Se l’array è già ordinato, il tempo è Θ(n). Con valori in ordine casuale è in media Θ(n²). L’ordine inverso è il caso peggiore e richiede anch’esso tempo quadratico.
Esempio semplice
Inserire 1 prima di 3, quindi scorrere di nuovo 3 da parte per inserire 2. Stampa i valori ordinati.
All’inizio3 1 2
Risultato1 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
}
}
Output
1
2
3
Esempi di vita quotidiana
Inserire un nuovo biglietto
Un impiegato tiene i biglietti 2, 5 e 8 in ordine. Dove va il biglietto 6?
All’inizio2 5 8 +6
Risultato2 5 6 8
Slide 8 destra. L'apertura dopo il 5 è la posizione di inserimento.
Aggiungere un appuntamento al mattino
Il tuo diario inizia alle 10 e alle 12. Aggiungi un appuntamento alle 9.
All’inizio10 12 +9
Risultato9 10 12
Entrambe le future assegnazioni spostano di una posizione per far spazio.
Aggiungere un pagamento arrivato tardi
Un registro ordinato termina nei giorni 4 e 6. Arriva un pagamento per il giorno 7. Che cosa cambia?
All’inizio4 6 +7
Risultato4 6 7
L'ultimo giorno esistente precede già 7. Appenderlo senza spostare le altre voci.
Costo e limiti
Insertion sort funziona bene su liste corte o quasi ordinate. Ordine inverso richiede O(n²) spostamenti e confronti.
Complessità temporale
Caso migliore: Θ(n)
Caso medio: Θ(n²)
Caso peggiore: Θ(n²)
Insertion sort in Go
Codice sorgente in 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)
}
Output
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Annunci
Segui l’esempio passo per passo
Inizia con [15, 3, 12, 6, -9, 9, 0].
Inizia con 15 come prefisso ordinato. Salva il valore successivo, 3.
Passare 15 un posto a destra e inserire 3 all'inizio. Il prefisso è ora [3, 15].
Per ogni valore rimanente, spostare solo valori più grandi prima di inserire. I valori uguali mantengono il loro ordine originale.
Insertion sort in Go, passo per passo
Codice sorgente in 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)
}
Output
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15