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.py
values = [3, 1, 2]
i = 1
while i < 3:
key = values[i]
j = i - 1
while j >= 0 and values[j] > key:
values[j + 1] = values[j]
j -= 1
values[j + 1] = key
i += 1
i = 0
while i < 3:
print(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 Python
Codice sorgente in Python
class InsertionSortExample:
def __init__(self):
pass
def insertionSort(self, arr):
for i in range(len(arr)):
temp = arr[i]
holePosition = i
while(holePosition > 0 and arr[holePosition - 1] > temp):
arr[holePosition] = arr[holePosition - 1]
holePosition -= 1
arr[holePosition] = temp
return arr
def printArray(self, arr):
string = " ".join([str(item) for item in arr]);
print(string)
obj = InsertionSortExample()
arr = [15, 3, 12, 6, -9, 9, 0]
print("Before Sorting: ")
obj.printArray(arr)
result = obj.insertionSort(arr)
print("After Sorting: ")
obj.printArray(result)
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 Python, passo per passo
Codice sorgente in Python
class InsertionSortExample:
def __init__(self):
pass
def insertionSort(self, arr):
# Un-sorted array from position 1 to length -1
for i in range(len(arr)):
# 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 and arr[holePosition - 1] > temp):
arr[holePosition] = arr[holePosition - 1]
holePosition -= 1
# Once the comparison done, move the value in temp variable to the lastly marked empty position
arr[holePosition] = temp
# Return the sorted array
return arr
def printArray(self, arr):
# Loop the item and print each item in the console with white space seperated
string = " ".join([str(item) for item in arr]);
print(string)
obj = InsertionSortExample()
arr = [15, 3, 12, 6, -9, 9, 0]
print("Before Sorting: ")
obj.printArray(arr)
result = obj.insertionSort(arr)
print("After Sorting: ")
obj.printArray(result)
Output
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15