Implementing Array Algorithms · Implementación de algoritmos de arrays
| English | Español |
|---|---|
| traversal/træˈvɜːsl/ | recorrido |
| index/ˈɪndeks/ | índice |
| linear search/ˈlɪnɪə sɜːtʃ/ | búsqueda lineal |
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 estándar de arrays
- La mayoría de las tareas con arrays consisten en una travesía 遍历 más uno de los pocos patrones estándar.
- Suma / promedio: acumular un total, luego dividir por
length. - Conteo: incrementar cuando un elemento coincide con una condición.
- Mínimo / máximo: rastrear el valor más pequeño o más grande visto hasta ahora.
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.
Encontrar el máximo
- Iniciar
max = a[0](el primer elemento), luego realizar la travesía desde el índice1. if (a[i] > max) { max = a[i]; }dentro del bucle.- Después del bucle,
maxcontiene el valor más grande del array. - Empezar desde el primer elemento, no
0—0podría ser mayor que todos los 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).
Buscar un valor
- Para verificar si un valor está presente, realizar una travesía y comparar cada elemento.
- Devolver el índice 下标 donde se encuentra, o
-1si el bucle termina sin coincidencia. if (a[i] == target) return i;dentro del bucle;return -1;después.- Esto es una búsqueda lineal 线性查找 (la Unidad 4.14 lo cubre en profundidad).
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.
Desplazamiento y modificación
- Algunos algoritmos mueven o cambian elementos — p. ej., desplazar todo a la izquierda, o duplicar cada valor.
- La modificación necesita el bucle indexado para poder asignar
a[i] = .... - Cuidado con los límites al leer
a[i+1]— el último índice no tiene vecino. - Rastrear los índices cuidadosamente para evitar un acceso fuera de rango.
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.
Inicializar una búsqueda de max/min con el PRIMER elemento, no 0. int max = 0; falla si todos los valores son negativos (informaría incorrectamente 0). Usar int max = a[0]; e iniciar el bucle en el índice 1. Y cuando un algoritmo lee a[i+1], detener el bucle en i < a.length - 1, o la última iteración leerá más allá del 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.
Encontrar el 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 pasa a ser9.
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.
Los algoritmos de arrays combinan una travesía con un patrón: suma/promedio, conteo, mínimo/máximo, o búsqueda (devuelve el índice o -1). Inicializar min/max con el primer elemento, no 0. Modificar elementos necesita el bucle indexado, y leer a[i+1] necesita un límite más ajustado para mantenerse dentro del rango.
Finding the maximum · Encontrar el máximo
max starts at a[0]=3, becomes 9, then stays (a = {3,9,5}). · max comienza en a[0]=3, se convierte en 9, luego permanece igual (a = {3,9,5}).
To find the maximum of an array, you should initialize max to... · Para encontrar el máximo de un array, debes inicializar max en...
Starting at 0 fails if all values are negative. · Comenzar en 0 falla si todos los valores son negativos.
For a = {3, 9, 5}, what is the maximum value? · Para a = {3, 9, 5}, ¿cuál es el valor máximo?
9 is the largest element. · 9 es el elemento más grande.
A linear search returns what if the target is not found? · Una búsqueda lineal devuelve qué si no se encuentra el objetivo?
By convention, -1 means 'not found'. · Por convención, -1 significa 'no encontrado'.
An algorithm that reads a[i+1] should loop while... · Un algoritmo que lee a[i+1] debe iterar mientras...
Stopping one early keeps a[i+1] in bounds. · Detenerse una iteración antes mantiene a[i+1] dentro de límites válidos.
Modifying array elements (a[i] = ...) requires the indexed loop, not for-each. · Modificar elementos de array (a[i] = ...) requiere el bucle indexado, no for-each.
for-each can't assign back into the array. · for-each no puede asignar de vuelta al array.