Sorting: selection and insertion sort · Ordenação: selection sort e insertion sort
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.
Colocando um array em ordem
- Ordenação significa colocar os valores de um array em ordem, geralmente do menor para o maior.
- Na prova AP CSA você deve saber escrever e rastrear duas ordenações: selection sort e insertion sort.
- Você também precisa rastrear (mas não escrever) uma terceira ordenação: merge sort. Vamos ver as três aqui.
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.
Selection sort: a ideia
- Percorra o array da esquerda para a direita.
- Em cada posição
i, encontre o menor valor na parte ainda não ordenada (deiaté o fim). - Troque esse menor valor para a posição
i. Agora0..iestá ordenado. - Repita até que todo o array esteja em ordem.
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.
Selection sort: um rastreamento
- Vamos ordenar
{5, 2, 4, 1, 3}. A parte em negrito já está ordenada. - Cada passada escolhe o menor valor do resto e o troca para a 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.
Insertion sort: a ideia
- Pense em segurar cartas de baralho e adicionar uma carta de cada vez no lugar certo.
- Comece no índice
1. Chame esse valor de chave. - Deslize os valores maiores à esquerda uma posição para a direita, até a chave caber.
- Coloque a chave no espaço vazio. Agora tudo à esquerda 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.
Insertion sort: um rastreamento
- Ordene
{5, 2, 4, 1, 3}novamente. A parte em negrito permanece ordenada enquanto avançamos. - O
keyé o valor que estamos inserindo em cada passagem.
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.
Merge sort: apenas rastreamento
- Merge sort usa recursão (lição 15). Você não o escreve na prova, mas deve rastrear ele.
- Divida o array pela metade repetidamente, até que cada peça tenha um valor.
- Mescle pares de peças de volta juntas, mantendo-as sempre em ordem.
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.
Merge sort: um rastreamento
- Um valor já está "ordenado". Mesclar duas peças ordenadas dá uma peça maior ordenada.
split: [5, 2, 4, 1]
[5, 2] [4, 1]
[5] [2] [4] [1]
merge: [2, 5] [1, 4]
merge: [1, 2, 4, 5]
- Selection sort e insertion sort são lentos em arrays grandes (fazem cerca de n² passos).
- Merge sort é mais rápido em arrays grandes (cerca de n·log n passos). É por isso que importa.
Common mistakes
- Selection and insertion sort are both O(n²).
- Trace a small array by hand to check your sort.
Erros comuns
- Selection sort e insertion sort são ambos O(n²).
- Rastreie um array pequeno à mão para verificar sua ordenação.
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.
Agora você tenta
- Cada tarefa lhe dá um esqueleto de método com um TODO. Ordene o array in place (altere
amesmo). - Um Harness oculto ordena vários arrays e verifica o resultado.
- Pressione Run para compilar, depois Check answer.
Selection / insertion sort
Sorting compares and swaps until the list is ordered. · Ordenação compara e troca até que a lista esteja ordenada.
Complete selectionSort(int[] a) so it sorts the array in place from small to large, using selection sort. The checker tests several arrays. · Complete selectionSort(int[] a) para ordenar o array in loco de pequeno para grande, usando selection sort. O verificador testa vários arrays.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete insertionSort(int[] a) so it sorts the array in place from small to large, using insertion sort. The checker tests several arrays. · Complete insertionSort(int[] a) para ordenar o array in loco de pequeno para grande, usando insertion sort. O verificador testa vários arrays.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
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. · Complete isSorted(int[] a) retornando true se o array estiver em ordem de pequeno para grande (cada item é <= o próximo), senão false. Um array vazio ou de um único item conta como ordenado.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.