La ordenación por inserción amplía la parte ordenada de la izquierda con un valor cada vez. Desplaza una posición a la derecha los valores mayores y coloca el nuevo valor en el hueco. Si el arreglo ya está ordenado, el tiempo es Θ(n). Con valores en orden aleatorio es Θ(n²) de media. El orden inverso es el peor caso y también requiere tiempo cuadrático.
Ejemplo sencillo
Insertar 1 antes de 3, luego deslizar 3 a un lado otra vez para insertar 2. Imprima los valores ordenados.
Al empezar3 1 2
Resultado1 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
Salida
1
2
3
Ejemplos de la vida diaria
Insertar un nuevo turno
Un empleado mantiene los billetes 2, 5 y 8 en orden. ¿Dónde debería ir el billete 6?
Al empezar2 5 8 +6
Resultado2 5 6 8
Diapositiva 8 derecha. El punto abierto después de 5 es la posición de inserción.
Añadir una cita por la mañana
Su diario comienza a las 10 y 12. Añádase una cita a las 9.
Al empezar10 12 +9
Resultado9 10 12
Ambas citas más tarde cambian una posición para hacer espacio.
Añadir un pago que llegó tarde
Un libro de cuentas ordenado termina en los días 4 y 6. Llega un pago para el día 7. ¿Qué cambia?
Al empezar4 6 +7
Resultado4 6 7
El último día existente ya precede 7. Apéndela sin cambiar las otras entradas.
Coste y límites
El ordenamiento por inserción funciona bien en listas cortas o casi ordenadas. Orden inverso requiere O(n²) movimientos y comparaciones.
Complejidad temporal
Mejor caso: Θ(n)
Caso promedio: Θ(n²)
Peor caso: Θ(n²)
Ordenación por inserción en Python
Código fuente en 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)
Salida
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Anuncios
Sigue el ejemplo paso a paso
Empieza con [15, 3, 12, 6, -9, 9, 0].
Comienza con 15 como el prefijo clasificado. Ahorre el siguiente valor, 3.
Cambie 15 un lugar a la derecha e inserte 3 al principio. El prefijo es ahora [3, 15].
Para cada valor restante, cambiar sólo valores más grandes antes de insertarlo. Los valores iguales mantienen su orden original.
Ordenación por inserción en Python paso a paso
Código fuente en 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)
Salida
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15