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
Main.java
public class Main {
public static void main(String[] args) {
int[] values = {3, 1, 2};
int i = 1;
while (i < 3) {
int key = values[i];
int 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) {
System.out.println(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 Java
Código fuente en Java
class InsertionSortExample {
public void insertionSort(int[] arr) {
for(int i = 1; i < arr.length; i++) {
int temp = arr[i];
int holePosition = i;
while(holePosition > 0 && arr[holePosition - 1] > temp) {
arr[holePosition] = arr[holePosition - 1];
holePosition--;
}
arr[holePosition] = temp;
}
}
public void printArray(int[] arr) {
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
InsertionSortExample obj = new InsertionSortExample();
int[] arr = { 15, 3, 12, 6, -9, 9, 0 };
System.out.print("Before Sorting: ");
obj.printArray(arr);
obj.insertionSort(arr);
System.out.print("After Sorting: ");
obj.printArray(arr);
}
}
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 Java paso a paso
Código fuente en Java
class InsertionSortExample {
public void insertionSort(int[] arr) {
// Un-sorted array from position 1 to length -1
for(int i = 1; i < arr.length; i++) {
// Take the left most item in an un-sorted array to temp variable
int temp = arr[i];
// Mark the left most position as empty or hole
int 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(int[] arr) {
// Loop the item and print each item in the console with white space seperated
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
InsertionSortExample obj = new InsertionSortExample();
int[] arr = { 15, 3, 12, 6, -9, 9, 0 };
System.out.print("Before Sorting: ");
obj.printArray(arr);
obj.insertionSort(arr);
System.out.print("After Sorting: ");
obj.printArray(arr);
}
}
Salida
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15