Sorting: bubble, selection, and insertion · Ordenação: bubble, selection e insertion
Putting an array in order
- Sorting rearranges an array so the items go from smallest to largest.
- We sort in place: we move items around inside the same array, with no return value.
- Three classic methods do this: bubble, insertion, and selection sort.
Colocando um array em ordem
- Ordenação reorganiza uma matriz para que os itens fiquem do menor para o maior.
- Ordenamos no local: movemos itens dentro da mesma matriz, sem valor de retorno.
- Três métodos clássicos fazem isso: ordenação bolha, inserção e seleção.
Swapping two elements
- Every sort needs to swap two items. Save one in a temporary, then overwrite.
int t = a[i]; a[i] = a[j]; a[j] = t;exchanges positionsiandj.- Forgetting the temporary loses one of the values — always keep it.
Trocando dois elementos
- Toda ordenação precisa trocar dois itens. Salve um em temporário, depois sobrescreva.
int t = a[i]; a[i] = a[j]; a[j] = t;troca as posiçõesiej.- Esquecer o temporário perde um dos valores — sempre mantenha-o.
Bubble sort
- Go through the array and compare each pair of neighbours:
a[j]anda[j + 1]. - If they are in the wrong order, swap them. The biggest value "bubbles" to the end.
- Repeat the passes until the whole array is in order.
Bubble sort
- Passe pela matriz e compare cada par de vizinhos:
a[j]ea[j + 1]. - Se estiverem na ordem errada, troque-os. O maior valor "borbulha" para o final.
- Repita as passagens até que toda a matriz esteja em ordem.
Insertion sort
- Treat the left part of the array as already sorted, and grow it one item at a time.
- Take the next item as a key, shift bigger sorted items to the right, then drop the key into the gap.
- This is how many people sort playing cards in their hand.
Insertion sort
- Trate a parte esquerda da matriz como já ordenada, e cresça-a um item de cada vez.
- Pegue o próximo item como chave, desloque os itens maiores ordenados para a direita, depois insira a chave no espaço.
- É assim que muitas pessoas ordenam cartas na mão.
#include <stdio.h>
int main(void) {
int a[] = {3, 1, 2};
// one bubble pass: compare neighbours and swap if out of order
for (int j = 0; j < 2; j++) {
if (a[j] > a[j + 1]) {
int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
}
printf("%d %d %d\n", a[0], a[1], a[2]); // 1 2 3
return 0;
}
Common mistakes
- Bubble, selection and insertion sort are all O(n²).
- Trace a small array by hand to check your sort.
Erros comuns
- Bolha, seleção e inserção são todas O(n²).
- Rastreie um array pequeno à mão para verificar sua ordenação.
Now you try
- Sort ascending (smallest first), in place, with no return value.
- The checker tries several arrays, including negatives and an already-sorted one.
- Do not write a
main— the checker provides one.
Agora você tenta
- Ordene ascendente (menores primeiro), no local, sem valor de retorno.
- O verificador testa várias matrizes, incluindo negativas e uma já ordenada.
- Não escreva um
main— o verificador fornece um.
Watch a sort run · Assista uma ordenação rodar
Bubble / selection / insertion all compare and swap into order. · Bubble / selection / insertion todos comparam e trocam para ordenar.
Complete void swap(int a[], int i, int j) so it exchanges the items at index i and · e j, in place (no return). Do not · não write a main. · Complete void swap(int a[], int i, int j) para trocar os itens nos índices i e j, in-place (sem retorno). Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete void bubble_sort(int a[], int n) so it sorts the array ascending, in place, using bubble sort. Do not · não write a main. · Complete void bubble_sort(int a[], int n) para ordenar o array em ordem crescente, in-place, usando bubble sort. Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Complete void insertion_sort(int a[], int n) so it sorts the array ascending, in place, using insertion sort (take each item as a key and shift bigger items right). Do not · não write a main. · Complete void insertion_sort(int a[], int n) para ordenar o array em ordem crescente, in-place, usando insertion sort (pegue cada item como chave e desloque itens maiores para a direita). Não escreva um main.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.