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
Lesson.groovy
def values = [3, 1, 2]
def i = 1
while (i < 3) {
def key = values[i]
def j = i - 1
while ((j >= 0) && (values[j] > key)) {
values[j + 1] = values[j]
j -= 1
}
values[j + 1] = key
i += 1
}
i = 0
while (i < 3) {
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 Groovy
Codice sorgente in Groovy
class InsertionSortExample {
public void insertionSort(arr) {
def lastIndex = arr.length - 1
for (i in 0..lastIndex) {
def temp = arr[i]
def holePosition = i
while(holePosition > 0 && arr[holePosition - 1] > temp) {
arr[holePosition] = arr[holePosition - 1]
holePosition--
}
arr[holePosition] = temp
}
}
public void printArray(arr) {
def lastIndex = arr.length - 1
for (i in 0..lastIndex) {
def num = arr[i]
print(num + " ")
}
println("")
}
public static void main(String[] args) {
def obj = new InsertionSortExample()
def arr = [15, 3, 12, 6, -9, 9, 0].toArray()
print("Before Sorting: ")
obj.printArray(arr)
obj.insertionSort(arr)
print("After Sorting: ")
obj.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 Groovy, passo per passo
Codice sorgente in Groovy
class InsertionSortExample {
public void insertionSort(arr) {
def lastIndex = arr.length - 1
// Un-sorted array from position 1 to length -1
for (i in 0..lastIndex) {
// Take the left most item in an un-sorted array to temp variable
def temp = arr[i]
// Mark the left most position as empty or hole
def 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 void printArray(arr) {
def lastIndex = arr.length - 1
// Loop the item and print each item in the console with white space seperated
for (i in 0..lastIndex) {
def num = arr[i]
print(num + " ")
}
println("")
}
public static void main(String[] args) {
def obj = new InsertionSortExample()
def arr = [15, 3, 12, 6, -9, 9, 0].toArray()
print("Before Sorting: ")
obj.printArray(arr)
obj.insertionSort(arr)
print("After Sorting: ")
obj.printArray(arr)
}
}
Output
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15