Sorting: selection and insertion sort · Ordenación: selección e inserción
Putting an array in order
- Sorting means putting the values of an array in order, usually from small to large.
- On the AP CSA exam you must be able to write and trace two sorts: selection sort and insertion sort.
- You also need to trace (but not write) a third sort: merge sort. We look at all three here.
Ordenar un array
- Ordenar significa colocar los valores de un array en orden, generalmente de menor a mayor.
- En el examen AP CSA debes ser capaz de escribir y rastrear dos tipos de ordenamiento: ordenamiento por selección y ordenamiento por inserción.
- También necesitas rastrear (pero no escribir) un tercer tipo de ordenamiento: ordenamiento por fusión. Revisamos los tres aquí.
Selection sort: the idea
- Walk through the array from left to right.
- At each spot
i, find the smallest value in the part that is still unsorted (fromito the end). - Swap that smallest value into spot
i. Now0..iis sorted. - Repeat until the whole array is in order.
Ordenamiento por selección: la idea
- Recorre el array de izquierda a derecha.
- En cada posición
i, encuentra el valor más pequeño en la parte que aún está desordenada (desdeihasta el final). - Intercambia ese valor más pequeño hacia la posición
i. Ahora0..iestá ordenado. - Repite hasta que todo el array esté en orden.
public class Sorter {
public static void selectionSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
int min = i; // index of smallest so far
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[min]) {
min = j; // found a smaller value
}
}
int temp = a[min]; // swap a[i] and a[min]
a[min] = a[i];
a[i] = temp;
}
}
}
Selection sort: a trace
- Let us sort
{5, 2, 4, 1, 3}. The bold part is already sorted. - Each pass picks the smallest value from the rest and swaps it to the front.
Ordenamiento por selección: rastreo
- Vamos a ordenar
{5, 2, 4, 1, 3}. La parte en negrita ya está ordenada. - Cada pasada selecciona el valor más pequeño del resto y lo intercambia al frente.
start: [5, 2, 4, 1, 3]
i=0 smallest=1 → swap a[0],a[3]: [1 | 2, 4, 5, 3]
i=1 smallest is already 2 → no move: [1, 2 | 4, 5, 3]
i=2 smallest=3 → swap a[2],a[4]: [1, 2, 3 | 5, 4]
i=3 smallest=4 → swap a[3],a[4]: [1, 2, 3, 4 | 5]
done: [1, 2, 3, 4, 5]
Insertion sort: the idea
- Think of holding playing cards and adding one card at a time into the right place.
- Start at index
1. Call this value the key. - Slide bigger values on the left one step to the right, until the key fits.
- Drop the key into the gap. Now everything to the left is sorted.
Ordenamiento por inserción: la idea
- Piensa en sostener cartas de juego y agregar una carta a la vez en su lugar correcto.
- Comienza en el índice
1. Llama a este valor la clave. - Desliza los valores mayores situados a la izquierda una posición a la derecha, hasta que la clave encaje.
- Coloca la clave en el hueco. Ahora todo a la izquierda está ordenado.
public class Sorter {
public static void insertionSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int key = a[i]; // the value to place
int j = i - 1;
while (j >= 0 && a[j] > key) { // shift bigger values right
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = key; // drop key into the gap
}
}
}
Insertion sort: a trace
- Sort
{5, 2, 4, 1, 3}again. The bold part stays sorted as we go. - The
keyis the value we are inserting on each pass.
Ordenamiento por inserción: rastreo
- Ordena
{5, 2, 4, 1, 3}nuevamente. La parte en negrita permanece ordenada mientras avanzamos. - La
keyes el valor que estamos insertando en cada pasada.
start: [5, 2, 4, 1, 3]
i=1 key=2 → shift 5 right, place 2: [2, 5 | 4, 1, 3]
i=2 key=4 → shift 5 right, place 4: [2, 4, 5 | 1, 3]
i=3 key=1 → shift 5,4,2 right, place 1: [1, 2, 4, 5 | 3]
i=4 key=3 → shift 5,4 right, place 3: [1, 2, 3, 4, 5]
done: [1, 2, 3, 4, 5]
Merge sort: trace only
- Merge sort uses recursion (lesson 15). You do not write it on the exam, but you must trace it.
- Split the array in half again and again, until each piece has one value.
- Merge pairs of pieces back together, always keeping them in order.
Ordenamiento por fusión: solo rastreo
- El ordenamiento por fusión usa recursividad (lección 15). No lo escribas en el examen, pero debes rastrearlo.
- Divide el array en mitades repetidamente, hasta que cada fragmento tenga un solo valor.
- Fusiona pares de fragmentos juntos, manteniéndolos siempre en orden.
Merge sort: a trace
- One value is already "sorted". Merging two sorted pieces gives a bigger sorted piece.
- Selection and insertion sort are slow on big arrays (they do about n² steps).
- Merge sort is faster on big arrays (about n·log n steps). That is why it matters.
Ordenamiento por fusión: rastreo
- Un valor ya está "ordenado". Fusionar dos piezas ordenadas da como resultado una pieza más grande ordenada.
split: [5, 2, 4, 1]
[5, 2] [4, 1]
[5] [2] [4] [1]
merge: [2, 5] [1, 4]
merge: [1, 2, 4, 5]
- Los ordenamientos por selección e inserción son lentos en arrays grandes (realizan aproximadamente n² pasos).
- El ordenamiento por fusión es más rápido en arrays grandes (aproximadamente n·log n pasos). Por eso es importante.
Common mistakes
- Selection and insertion sort are both O(n²).
- Trace a small array by hand to check your sort.
Errores comunes
- Tanto el ordenamiento por selección como el de inserción son O(n²).
- Rastrea un array pequeño a mano para verificar tu ordenamiento.
Now you try
- Each task gives you a method skeleton with a TODO. Sort the array in place (change
aitself). - A hidden Harness sorts several arrays and checks the result.
- Press Run to compile, then Check answer.
Ahora tú intentas
- Cada tarea te proporciona un esqueleto de método con un TODO. Ordena el array in situ (modifica
adirectamente). - Una Caja de pruebas oculta ordenará varios arrays y verificará el resultado.
- Presiona Ejecutar para compilar, luego Verificar respuesta.
Selection / insertion sort · Ordenación por selección / inserción
Sorting compares and swaps until the list is ordered. · La ordenación compara e intercambia hasta que la lista está ordenada.
Complete selectionSort(int[] a) so it sorts the array in place from small to large, using selection sort. The checker tests several arrays. · Completa selectionSort(int[] a) para que ordene el array in situ de menor a mayor, usando ordenación por selección. El comprobador prueba varios arrays.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete insertionSort(int[] a) so it sorts the array in place from small to large, using insertion sort. The checker tests several arrays. · Completa insertionSort(int[] a) para que ordene el array in situ de menor a mayor, usando ordenación por inserción. El comprobador prueba varios arrays.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete isSorted(int[] a) returning true if the array is in order from small to large (each item is <= the next), else false. An empty or one-item array counts as sorted. · Completa isSorted(int[] a) devolviendo true si el array está ordenado de menor a mayor (cada elemento es <= al siguiente), o false en caso contrario. Un array vacío o de un solo elemento se considera ordenado.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.