Implementing Array Algorithms · Implementando Algoritmos de Array
| English | Português |
|---|---|
| traversal/træˈvɜːsl/ | traversing |
| index/ˈɪndeks/ | interface |
| linear search/ˈlɪnɪə sɜːtʃ/ | busca linear |
Standard array algorithms
- Most array tasks are a traversal 遍历 plus one of a few standard patterns.
- Sum / average: accumulate a total, then divide by
length. - Count: increment when an element matches a condition.
- Min / max: track the smallest or largest seen so far.
Algoritmos padrão de arrays
- A maioria das tarefas de array é uma travessia 遍历 mais um de alguns padrões padrão.
- Soma / média: acumule um total, depois divida por
length. - Contagem: incrementie quando um elemento corresponde a uma condição.
- Mínimo / máximo: acompanhe o menor ou maior visto até agora.
Finding the maximum
- Start
max = a[0](the first element), then traverse from index1. if (a[i] > max) { max = a[i]; }inside the loop.- After the loop,
maxholds the largest value in the array. - Start from the first element, not
0—0could be larger than every value.
Encontrando o máximo
- Inicie com
max = a[0](o primeiro elemento), depois faça a travessia a partir do índice1. if (a[i] > max) { max = a[i]; }dentro do loop.- Após o loop,
maxconterá o maior valor do array. - Comece pelo primeiro elemento, não por
0—0poderia ser maior que todos os valores.
Searching for a value
- To check if a value is present, traverse and compare each element.
- Return the index 下标 where it's found, or
-1if the loop finishes without a match. if (a[i] == target) return i;inside the loop;return -1;after.- This is a linear search 线性查找 (Unit 4.14 covers it in depth).
Buscando um valor
- Para verificar se um valor está presente, faça a travessia e compare cada elemento.
- Retorne o índice 下标 onde ele foi encontrado, ou
-1se o loop terminar sem correspondência. if (a[i] == target) return i;dentro do loop;return -1;depois.- Isso é uma busca linear 线性查找 (Unidade 4.14 cobre isso em profundidade).
Shifting and modifying
- Some algorithms move or change elements — e.g. shift everything left, or double each value.
- Modifying needs the indexed loop so you can assign
a[i] = .... - Watch bounds when reading
a[i+1]— the last index has no neighbor. - Trace the indices carefully to avoid an out-of-bounds access.
Deslocamento e modificação
- Alguns algoritmos movem ou alteram elementos — ex.: deslocar tudo para a esquerda ou dobrar cada valor.
- Modificar exige o loop indexado para poder atribuir
a[i] = .... - Cuidado com os limites ao ler
a[i+1]— o último índice não tem vizinho. - Rastreie os índices cuidadosamente para evitar acesso fora dos limites.
Initialize a max/min search with the FIRST element, not 0. int max = 0; fails if every value is negative (it would wrongly report 0). Use int max = a[0]; and start the loop at index 1. And when an algorithm reads a[i+1], stop the loop at i < a.length - 1, or the last iteration reads past the end.
Inicialize uma busca de máx/min com o PRIMEIRO elemento, não com 0. int max = 0; falha se todos os valores forem negativos (relataria erroneamente 0). Use int max = a[0]; e inicie o loop no índice 1. E quando um algoritmo lê a[i+1], pare o loop em i < a.length - 1, ou a última iteração lerá além do final.
Finding the maximum of a:
int max = a[0];for (int i = 1; i < a.length; i++) { if (a[i] > max) max = a[i]; }- For
a = {3, 9, 5}: max becomes9.
Encontrando o máximo de a:
int max = a[0];for (int i = 1; i < a.length; i++) { if (a[i] > max) max = a[i]; }- Para
a = {3, 9, 5}: max torna-se9.
Array algorithms combine a traversal with a pattern: sum/average, count, min/max, or search (return the index or -1). Initialize a min/max with the first element, not 0. Modifying elements needs the indexed loop, and reading a[i+1] needs a tighter bound to stay in range.
Algoritmos de array combinam uma travessia com um padrão: soma/média, contagem, min/max, ou busca (retorna o índice ou -1). Inicialize min/max com o primeiro elemento, não com 0. Modificar elementos exige o loop indexado, e ler a[i+1] exige um limite mais restrito para permanecer na faixa.
Finding the maximum · Encontrando o máximo
max starts at a[0]=3, becomes 9, then stays (a = {3,9,5}). · max começa em a[0]=3, torna-se 9, depois permanece (a = {3,9,5}).
To find the maximum of an array, you should initialize max to... · Para encontrar o máximo de um array, você deve inicializar max como...
Starting at 0 fails if all values are negative. · Começar em 0 falha se todos os valores forem negativos.
For a = {3, 9, 5}, what is the maximum value? · Para a = {3, 9, 5}, qual é o valor máximo?
9 is the largest element. · 9 é o maior elemento.
A linear search returns what if the target is not found? · Uma busca linear retorna o quê se o alvo não for encontrado?
By convention, -1 means 'not found'. · Por convenção, -1 significa 'não encontrado'.
An algorithm that reads a[i+1] should loop while... · Um algoritmo que lê a[i+1] deve loopar enquanto...
Stopping one early keeps a[i+1] in bounds. · Parar um pouco cedo mantém a[i+1] dentro dos limites.
Modifying array elements (a[i] = ...) requires the indexed loop, not for-each. · Modificando elementos de array (a[i] = ...) requer o laço indexado, não for-each.
for-each can't assign back into the array. · for-each não pode atribuir de volta no array.