<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Arreglos y Matrices &#8211; PSeInt.org</title>
	<atom:link href="https://pseint.org/arreglos-y-matrices/feed/" rel="self" type="application/rss+xml" />
	<link>https://pseint.org</link>
	<description>Descargar Gratis, Versión Online y Ejercicios (2026)</description>
	<lastBuildDate>Sat, 07 Nov 2026 02:31:32 +0000</lastBuildDate>
	<language>es</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.1.4</generator>

<image>
	<url>https://pseint.org/wp-content/uploads/2026/01/favicon-150x150.png</url>
	<title>Arreglos y Matrices &#8211; PSeInt.org</title>
	<link>https://pseint.org</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Algoritmo para la Diagonal Principal de una Matriz en PSeInt: Guía y Diagrama</title>
		<link>https://pseint.org/diagonal-principal-matriz-pseint/</link>
		
		<dc:creator><![CDATA[El Profe Juan]]></dc:creator>
		<pubDate>Wed, 14 Oct 2026 16:32:02 +0000</pubDate>
				<category><![CDATA[Arreglos y Matrices]]></category>
		<guid isPermaLink="false">https://pseint.org/diagonal-principal-matriz-pseint/</guid>

					<description><![CDATA[Aprende a extraer y sumar la diagonal principal de una matriz en PSeInt. Optimización O(N), traza, diagonal secundaria y matriz identidad con diagrama DFD.]]></description>
										<content:encoded><![CDATA[<style>
.entry-title, h1.entry-title {
    max-width: 860px !important;
    margin-left: auto !important;
    margin-right: auto !important;
    text-wrap: balance !important;
    line-height: 1.25 !important;
}
</style>
<article style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1e293b; line-height: 1.8; max-width: 100%;">
<p>    <!-- 1. HEADER METADATA BADGES --></p>
<header style="margin-bottom: 35px;">
<div style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px;">
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #e0f2fe; color: #0369a1; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 700; text-transform: uppercase; line-height: 1.2;">Nivel: Intermedio</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #f1f5f9; color: #475569; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Estructura: Matrices Cuadradas (N x N)</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #fef3c7; color: #b45309; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Optimización: Ciclo Simple O(N)</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #ecfdf5; color: #047857; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">PSeInt: Compatible Estricto y Flexible</span>
        </div>
<p>        <!-- BLUF BOX (Bottom Line Up Front) --></p>
<div style="background: #f8fafc; border-left: 5px solid #2563eb; padding: 24px; border-radius: 0 10px 10px 0; box-shadow: 0 2px 4px rgba(0,0,0,0.03);">
<p style="margin: 0 0 12px 0; font-size: 1.12rem; color: #1e293b; font-weight: 600;">
                El <strong>algoritmo para la diagonal principal de una matriz en PSeInt</strong> procesa los elementos donde el índice de fila coincide exactamente con el índice de columna (<code>i = j</code>), cuya sumatoria define la <strong>Traza de la Matriz</strong> (\(\text{Traza}(M) = \sum_{i=1}^N M[i, i]\)).
            </p>
<p style="margin: 0; font-size: 0.98rem; color: #475569;">
                <strong>Optimización fundamental de complejidad:</strong> Aunque puede resolverse con dos ciclos anidados evaluando <code>Si i = j</code> (\(O(N^2)\)), la solución óptima utiliza un <strong>único ciclo Para</strong> que indexa directamente <code>matriz[i, i]</code>, reduciendo el costo computacional a \(O(N)\) lineal y ahorrando \(N^2 &#8211; N\) comprobaciones condicionales innecesarias.
            </p>
</p></div>
</header>
<p>    <!-- SECTION 1: THEORY & MATHEMATICAL FOUNDATIONS --></p>
<h2>Fundamentos Matemáticos de la Diagonal Principal y la Traza Matricial</h2>
<p>
        En el álgebra lineal, la noción de <strong>diagonal principal</strong> está restringida exclusivamente a las <strong>matrices cuadradas</strong> (aquellas con idéntico número de filas y columnas, \(F = C = N\)). Si una matriz es rectangular (\(F \neq C\)), carece de una diagonal principal canónica continua.
    </p>
<div style="background: #f1f5f9; border-left: 4px solid #0284c7; padding: 18px; border-radius: 0 8px 8px 0; margin: 20px 0; font-size: 0.95rem; color: #0f172a;">
        <strong>Propiedades algebraicas en una matriz cuadrada de orden \(N\):</strong></p>
<ul style="margin: 8px 0 0 0; padding-left: 20px; line-height: 1.7;">
<li><strong>Diagonal Principal:</strong> Conjunto de elementos \(M_{i, j}\) tales que \(i = j\) (ejemplo: \(M_{1,1}, M_{2,2}, M_{3,3}\)).</li>
<li><strong>Traza de la Matriz:</strong> Suma de las entradas sobre la diagonal: \(\text{Traza}(M) = M_{1,1} + M_{2,2} + \dots + M_{N,N}\).</li>
<li><strong>Diagonal Secundaria:</strong> Elementos opuestos donde \(i + j = N + 1\) (ejemplo: \(M_{1,3}, M_{2,2}, M_{3,1}\)).</li>
</ul></div>
<p>    <!-- COMPARISON TABLE: O(N^2) VS O(N) --></p>
<div style="overflow-x: auto; margin: 25px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.95rem; text-align: left; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
<thead style="background-color: #1e293b; color: #ffffff;">
<tr>
<th style="padding: 12px 16px;">Estrategia de Recorrido</th>
<th style="padding: 12px 16px;">Doble Ciclo Anidado con Condicional</th>
<th style="padding: 12px 16px;">Ciclo Simple Directo M[i, i] (Óptimo)</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 16px; font-weight: 600;">Complejidad Temporal</td>
<td style="padding: 12px 16px; color: #b45309; font-weight: 600;">\(O(N^2)\) cuadrática</td>
<td style="padding: 12px 16px; color: #166534; font-weight: 600;">\(O(N)\) lineal estricta</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 12px 16px; font-weight: 600;">Iteraciones en Matriz 10&#215;10</td>
<td style="padding: 12px 16px; color: #991b1b;">100 iteraciones y 100 evaluaciones Si</td>
<td style="padding: 12px 16px; color: #166534; font-weight: 600;">Solo 10 iteraciones directas (10x más rápido)</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 16px; font-weight: 600;">Consumo de Instrucciones</td>
<td style="padding: 12px 16px;">Evalúa 90 celdas que jamás pertenecerán a la diagonal</td>
<td style="padding: 12px 16px; color: #166534; font-weight: 600;">Acceso indexado inmediato sin bifurcaciones</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 12px 16px; font-weight: 600;">Estructura del Código</td>
<td style="padding: 12px 16px;"><code>Para i ... Para j ... Si i = j</code></td>
<td style="padding: 12px 16px; font-family: monospace;"><code>Para i &lt;- 1 Hasta N: suma &lt;- suma + M[i, i]</code></td>
</tr>
</tbody>
</table></div>
<p>    <!-- SECTION 2: EXERCISE 1 (CORE EFFICIENT O(N) ALGORITHM) --></p>
<h2>Ejercicio 1 Algoritmo Óptimo con Ciclo Simple O(N) para la Diagonal Principal</h2>
<p>
        El siguiente algoritmo define una matriz cuadrada de \(3 \times 3\), muestra la cuadrícula visual para el usuario y extrae los elementos diagonales calculando su suma total (traza) mediante un único <a href="/para-hasta-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">bucle Para</a>:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Perfil Estricto y Flexible)</span><br />
            <span style="background: #2563eb; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Optimización O(N)</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo DiagonalPrincipalOptima
    // 1. Declaración estricta previa a dimensiones
    Definir N, i, j, sumaDiagonal Como Entero
    Definir M Como Entero
    
    N &lt;- 3
    Dimension M[3, 3]
    
    // 2. Carga de datos de la matriz 3x3
    M[1, 1] &lt;- 8;  M[1, 2] &lt;- 3;  M[1, 3] &lt;- 5
    M[2, 1] &lt;- 2;  M[2, 2] &lt;- 9;  M[2, 3] &lt;- 4
    M[3, 1] &lt;- 7;  M[3, 2] &lt;- 1;  M[3, 3] &lt;- 6
    
    Escribir "=== MATRIZ CUADRADA 3x3 ==="
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        Escribir Sin Saltar "Fila ", i, ": [ "
        Para j &lt;- 1 Hasta N Con Paso 1 Hacer
            Escribir Sin Saltar M[i, j], " "
        FinPara
        Escribir "]"
    FinPara
    
    // 3. Inicialización del acumulador de traza
    sumaDiagonal &lt;- 0
    
    Escribir "--------------------------------------------"
    Escribir "=== ELEMENTOS DE LA DIAGONAL PRINCIPAL (i = j) ==="
    
    // 4. Extracción eficiente en tiempo lineal O(N)
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        Escribir "-> Posición [", i, ",", i, "] = ", M[i, i]
        sumaDiagonal &lt;- sumaDiagonal + M[i, i]
    FinPara
    
    // 5. Presentación de la Traza
    Escribir "--------------------------------------------"
    Escribir "Traza de la Matriz (Sumatoria): ", sumaDiagonal
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 3: FLOWCHART --></p>
<h2>Diagrama de Flujo del Algoritmo de la Diagonal Principal</h2>
<p>
        El diagrama de flujo en notación DFD de PSeInt refleja cómo la optimización lineal elimina el anidamiento de bucles para la extracción de la diagonal, ejecutando únicamente \(N\) ciclos simples:
    </p>
<figure style="margin: 30px auto; text-align: center; max-width: 780px;">
<div style="background: #ffffff; padding: 16px; border: 1px solid #e2e8f0; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.06);">
            <img decoding="async" src="https://pseint.org/wp-content/uploads/2026/11/diagonal-principal-matriz-pseint-diagrama-flujo.png" 
                 alt="Diagrama de flujo del algoritmo para extraer y sumar la diagonal principal de una matriz en PSeInt" 
                 style="max-width: 100%; height: auto; border-radius: 8px; display: block; margin: 0 auto;" />
        </div><figcaption style="margin-top: 10px; font-size: 0.88rem; color: #64748b; font-style: italic;">
            Figura 1. Diagrama de flujo oficial DFD en PSeInt con definición estricta, ciclo simple O(N) e indexación directa de las coordenadas homólogas M[i, i].<br />
        </figcaption></figure>
<p>    <!-- SECTION 4: TRACE TABLE --></p>
<h2>Prueba de Escritorio Detallada con Matrices Cuadradas Diversas</h2>
<p>
        A través de una prueba de escritorio formal evaluamos matrices de diferentes órdenes y características algebraicas para ratificar la consistencia del algoritmo:
    </p>
<div style="overflow-x: auto; margin: 25px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.9rem; text-align: center; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
<thead style="background-color: #1e293b; color: #ffffff;">
<tr>
<th style="padding: 10px 14px;">Escenario / Matriz</th>
<th style="padding: 10px 14px;">Orden (N)</th>
<th style="padding: 10px 14px;">Elementos Diagonales M[i, i]</th>
<th style="padding: 10px 14px;">Operación de Traza</th>
<th style="padding: 10px 14px;">Resultado Traza</th>
<th style="padding: 10px 14px;">Complejidad de Iteración</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">1. Matriz 3&#215;3 Base<br /><code>[8,3,5; 2,9,4; 7,1,6]</code></td>
<td style="padding: 10px 14px;">3</td>
<td style="padding: 10px 14px; font-family: monospace;">M[1,1]=8, M[2,2]=9, M[3,3]=6</td>
<td style="padding: 10px 14px;">8 + 9 + 6</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">23</td>
<td style="padding: 10px 14px; color: #166534; font-weight: 600;">3 iteraciones</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 10px 14px; font-weight: 600;">2. Matriz 4&#215;4 Extensa<br /><code>[1,0,0,0; 0,2,0,0; ...]</code></td>
<td style="padding: 10px 14px;">4</td>
<td style="padding: 10px 14px; font-family: monospace;">1, 2, 3, 4</td>
<td style="padding: 10px 14px;">1 + 2 + 3 + 4</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">10</td>
<td style="padding: 10px 14px; color: #166534; font-weight: 600;">4 iteraciones</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">3. Con Negativos y Ceros<br /><code>[-5, 2; 4, 0]</code></td>
<td style="padding: 10px 14px;">2</td>
<td style="padding: 10px 14px; font-family: monospace;">M[1,1]=-5, M[2,2]=0</td>
<td style="padding: 10px 14px;">(-5) + 0</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">-5</td>
<td style="padding: 10px 14px; color: #166534; font-weight: 600;">2 iteraciones</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 10px 14px; font-weight: 600;">4. Matriz Identidad 3&#215;3<br /><code>[1,0,0; 0,1,0; 0,0,1]</code></td>
<td style="padding: 10px 14px;">3</td>
<td style="padding: 10px 14px; font-family: monospace;">1, 1, 1</td>
<td style="padding: 10px 14px;">1 + 1 + 1</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">3</td>
<td style="padding: 10px 14px; color: #166534; font-weight: 600;">Traza = Orden N</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">5. Caso Borde Unitario 1&#215;1<br /><code>[42]</code></td>
<td style="padding: 10px 14px;">1</td>
<td style="padding: 10px 14px; font-family: monospace;">M[1,1]=42</td>
<td style="padding: 10px 14px;">42</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">42</td>
<td style="padding: 10px 14px; color: #166534; font-weight: 600;">1 iteración inmediata</td>
</tr>
</tbody>
</table></div>
<p>    <!-- SECTION 5: EXERCISE 2 (SECONDARY DIAGONAL) --></p>
<h2>Ejercicio 2 Extracción de la Diagonal Secundaria y Comparación Simétrica</h2>
<p>
        La <strong>diagonal secundaria</strong> conecta la esquina superior derecha con la esquina inferior izquierda. Los índices cumplen la relación \(i + j = N + 1\), lo que permite indexar la celda complementaria como <code>matriz[i, N - i + 1]</code> (técnica hermana a nuestro algoritmo de <a href="/invertir-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">inversión de arreglos por intercambio</a>):
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Diagonal Principal y Secundaria)</span><br />
            <span style="background: #059669; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Doble Diagonal</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo AmbasDiagonales
    Definir N, i, sumaPrin, sumaSec Como Entero
    Definir matriz Como Entero
    
    N &lt;- 3
    Dimension matriz[3, 3]
    
    matriz[1, 1] &lt;- 10; matriz[1, 2] &lt;- 20; matriz[1, 3] &lt;- 30
    matriz[2, 1] &lt;- 40; matriz[2, 2] &lt;- 50; matriz[2, 3] &lt;- 60
    matriz[3, 1] &lt;- 70; matriz[3, 2] &lt;- 80; matriz[3, 3] &lt;- 90
    
    sumaPrin &lt;- 0
    sumaSec &lt;- 0
    
    Escribir "=== EXTRACCIÓN SIMULTÁNEA DE DIAGONALES ==="
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        // Diagonal Principal: [i, i]
        sumaPrin &lt;- sumaPrin + matriz[i, i]
        Escribir "Principal [", i, ",", i, "]: ", matriz[i, i], " | ", Sin Saltar
        
        // Diagonal Secundaria: [i, N - i + 1]
        sumaSec &lt;- sumaSec + matriz[i, N - i + 1]
        Escribir "Secundaria [", i, ",", N - i + 1, "]: ", matriz[i, N - i + 1]
    FinPara
    
    Escribir "--------------------------------------------"
    Escribir "Suma Diagonal Principal:  ", sumaPrin
    Escribir "Suma Diagonal Secundaria: ", sumaSec
    Escribir "Diferencia absoluta:       ", abs(sumaPrin - sumaSec)
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 6: EXERCISE 3 (IDENTITY AND TRIANGULAR MATRICES) --></p>
<h2>Ejercicio 3 Verificación de Matriz Identidad y Matrices Triangulares</h2>
<p>
        La diagonal principal divide la matriz en dos regiones geométricas fundamentales: la <strong>triangular superior</strong> (donde \(i &lt; j\)) y la <strong>triangular inferior</strong> (donde \(i &gt; j\)). El siguiente código comprueba si una matriz cumple las condiciones para ser una <strong>Matriz Identidad</strong> (unos en la diagonal y ceros en el resto):
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Validación de Matriz Identidad)</span><br />
            <span style="background: #9333ea; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Verificación Álgebra</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo VerificarMatrizIdentidad
    Definir N, i, j Como Entero
    Definir esIdentidad Como Logico
    Definir id Como Entero
    
    N &lt;- 3
    Dimension id[3, 3]
    
    // Carga de una matriz identidad para comprobación
    id[1, 1] &lt;- 1; id[1, 2] &lt;- 0; id[1, 3] &lt;- 0
    id[2, 1] &lt;- 0; id[2, 2] &lt;- 1; id[2, 3] &lt;- 0
    id[3, 1] &lt;- 0; id[3, 2] &lt;- 0; id[3, 3] &lt;- 1
    
    esIdentidad &lt;- Verdadero
    
    // Verificación condicional de todos los elementos
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        Para j &lt;- 1 Hasta N Con Paso 1 Hacer
            Si i = j Entonces
                // La diagonal principal DEBE ser 1
                Si id[i, j] &lt;&gt; 1 Entonces
                    esIdentidad &lt;- Falso
                FinSi
            SiNo
                // Fuera de la diagonal DEBE ser 0
                Si id[i, j] &lt;&gt; 0 Entonces
                    esIdentidad &lt;- Falso
                FinSi
            FinSi
        FinPara
    FinPara
    
    Escribir "--------------------------------------------"
    Si esIdentidad Entonces
        Escribir "¡Validación exitosa! La matriz analizada ES una Matriz Identidad."
    SiNo
        Escribir "La matriz NO cumple las propiedades de la Matriz Identidad."
    FinSi
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 7: EXERCISE 4 (MODULARIZATION WITH FUNCTION) --></p>
<h2>Ejercicio 4 Modularización con Funciones para el Cálculo de la Traza</h2>
<p>
        Para integrar esta lógica en sistemas de álgebra computacional o simulaciones físicas, desacoplamos el cálculo mediante una <a href="/subproceso-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Función modular en PSeInt</a>:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Función Modular)</span><br />
            <span style="background: #0891b2; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Modular</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">// Función que calcula y devuelve la traza de cualquier matriz cuadrada
Funcion trazaResultado &lt;- CalcularTrazaMatriz(matrizRef Por Referencia, orden)
    Definir trazaResultado, k Como Entero
    trazaResultado &lt;- 0
    Para k &lt;- 1 Hasta orden Con Paso 1 Hacer
        trazaResultado &lt;- trazaResultado + matrizRef[k, k]
    FinPara
FinFuncion

Algoritmo PrincipalTrazaModular
    Definir dimMatriz, valorTraza Como Entero
    Definir tabla Cuadrada Como Entero
    
    dimMatriz &lt;- 3
    Dimension tabla[3, 3]
    
    tabla[1, 1] &lt;- 15; tabla[1, 2] &lt;- 4;  tabla[1, 3] &lt;- 9
    tabla[2, 1] &lt;- 3;  tabla[2, 2] &lt;- 20; tabla[2, 3] &lt;- 1
    tabla[3, 1] &lt;- 8;  tabla[3, 2] &lt;- 7;  tabla[3, 3] &lt;- 5
    
    // Invocación funcional
    valorTraza &lt;- CalcularTrazaMatriz(tabla, dimMatriz)
    
    Escribir "=== RESULTADO DE LA FUNCIÓN MODULAR ==="
    Escribir "La traza devuelta por la función es: ", valorTraza
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 8: COMMON MISTAKES --></p>
<h2>Errores Comunes al Trabajar con Diagonales en PSeInt</h2>
<p>
        Durante el tratamiento de diagonales matriciales surgen errores conceptuales y sintácticos frecuentes:
    </p>
<div style="display: flex; flex-direction: column; gap: 16px; margin: 25px 0;">
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">1. Aplicar la diagonal principal sobre matrices rectangulares</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Intentar calcular la traza de una matriz \(2 \times 5\) asumiendo que el límite es 5 causará que al llegar a <code>i = 3</code> se dispare el <a href="/error-303-pseint/" style="color: #9f1239; text-decoration: underline; font-weight: 700;">Error 303: Subíndice fuera de rango</a> porque solo existen 2 filas. Asegúrese de que la matriz sea estrictamente cuadrada (\(F = C\)).
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">2. Desperdicio de rendimiento mediante ciclos anidados</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Recorrer todas las filas y columnas para comprobar <code>Si i = j</code> no es un error sintáctico, pero sí un fallo grave de eficiencia algorítmica: incrementa innecesariamente la complejidad a \(O(N^2)\). La solución profesional siempre debe usar un solo índice: <code>M[i, i]</code>.
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">3. Error en la fórmula de la diagonal secundaria</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Escribir <code>M[i, N - i]</code> en lugar de <code>M[i, N - i + 1]</code> provocará que en la primera iteración se intente acceder a <code>N - 1</code> en vez de la última columna <code>N</code>, desfasando toda la línea diagonal.
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">4. Confusión entre traza y suma de toda la matriz</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                La traza corresponde exclusivamente a la suma de la diagonal principal. Si se requiere la sumatoria de todos los elementos de la cuadrícula, consulte nuestro <a href="/suma-matriz-pseint/" style="color: #9f1239; text-decoration: underline; font-weight: 700;">algoritmo para sumar una matriz completa en PSeInt</a>. Para más detalles consulte la <a href="/errores-comunes-pseint/" style="color: #9f1239; text-decoration: underline; font-weight: 700;">guía completa de errores en PSeInt</a>.
            </p>
</p></div>
</p></div>
<p>    <!-- SECTION 9: FAQ --></p>
<h2>Preguntas Frecuentes sobre la Diagonal Principal en PSeInt</h2>
<div style="display: flex; flex-direction: column; gap: 14px; margin: 25px 0;">
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Qué es exactamente la Traza de una matriz?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                En matemáticas, la traza es la suma de los elementos que integran la diagonal principal de una matriz cuadrada. Es un valor invariante ante cambios de base ampliamente usado en física, mecánica cuántica y procesamiento de imágenes.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Se puede extraer la diagonal de una matriz de cadenas o caracteres?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                Sí, la regla <code>M[i, i]</code> aplica a cualquier tipo de dato (Entero, Real, Carácter o Cadena), permitiendo por ejemplo concatenar palabras diagonales en juegos como sopas de letras.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Cuál es la relación entre la diagonal y la matriz transpuesta?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                Al transponer una matriz (\(M^T\)), los elementos fuera de la diagonal se intercambian (\(M^T_{i, j} = M_{j, i}\)), pero los elementos de la diagonal principal permanecen completamente inmutables ya que \(i = j\).
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Cómo se vincula este ejercicio con la serie de arreglos de PSeInt?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                Este ejercicio consolida el dominio de matrices cuadradas tras haber explorado la <a href="/suma-matriz-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">suma de matrices</a> y la familia de vectores lineales: <a href="/mayor-menor-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">máximo y mínimo en arreglos</a>, <a href="/buscar-en-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">búsqueda en vectores</a> y <a href="/contar-pares-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">conteo de pares</a>.
            </p>
</p></div>
</p></div>
<p>    <!-- CTA & INTERNAL NAVIGATION --></p>
<div style="background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); color: #ffffff; padding: 32px 24px; border-radius: 12px; margin: 40px 0; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.12);">
<h3 style="color: #ffffff; margin-top: 0; font-size: 1.35rem; margin-bottom: 12px;">Continúa Fortaleciendo tus Habilidades en Algoritmia</h3>
<p style="color: #94a3b8; font-size: 1rem; max-width: 680px; margin: 0 auto 24px auto; line-height: 1.6;">
            Explora más algoritmos resueltos paso a paso con diagramas de flujo interactivos, pruebas de escritorio y explicaciones detalladas para todos los niveles formativos.
        </p>
<div><a href="/ejercicios-resueltos/" style="display: inline-flex; align-items: center; justify-content: center; line-height: 1.2; background-color: #2563eb; color: #ffffff; padding: 12px 28px; border-radius: 8px; text-decoration: none; font-weight: 700; font-size: 1rem; transition: background 0.2s ease-in-out;">Explorar Catálogo de Ejercicios Resueltos</a></div>
</p></div>
</article>
<p><!-- JSON-LD SCHEMA METADATA --><br />
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "TechArticle",
      "headline": "Algoritmo para la Diagonal Principal de una Matriz en PSeInt: Guía y Diagrama",
      "description": "Aprende a extraer y sumar la diagonal principal de una matriz en PSeInt. Optimización O(N), traza, diagonal secundaria y matriz identidad con diagrama DFD.",
      "proficiencyLevel": "Intermediate",
      "inLanguage": "es",
      "author": {
        "@type": "Organization",
        "name": "PSeInt.org"
      }
    },
    {
      "@type": "HowTo",
      "name": "Cómo extraer y sumar la diagonal principal de una matriz en PSeInt",
      "description": "Procedimiento óptimo paso a paso para procesar los elementos diagonales M[i, i] en una matriz cuadrada con complejidad O(N).",
      "step": [
        {
          "@type": "HowToStep",
          "name": "Definir variables y dimensionar la matriz cuadrada",
          "text": "Declarar variables de tipo Entero y dimensionar la matriz cuadrada M[N, N]."
        },
        {
          "@type": "HowToStep",
          "name": "Inicializar el acumulador de la traza",
          "text": "Asignar 0 a la variable sumaDiagonal previa a la iteración."
        },
        {
          "@type": "HowToStep",
          "name": "Ejecutar el ciclo simple de recorrido O(N)",
          "text": "Crear un único bucle Para con i desde 1 hasta N, accediendo directamente a matriz[i, i]."
        },
        {
          "@type": "HowToStep",
          "name": "Mostrar los elementos y la traza final",
          "text": "Imprimir cada elemento diagonal y desplegar la sumatoria acumulada total."
        }
      ]
    },
    {
      "@type": "FAQPage",
      "mainEntity": [
        {
          "@type": "Question",
          "name": "¿Por qué es mejor usar un solo ciclo Para en vez de dos anidados?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Porque un solo ciclo accede directamente a las celdas M[i, i] en complejidad O(N), ahorrando N^2 - N comparaciones condicionales innecesarias."
          }
        },
        {
          "@type": "Question",
          "name": "¿Se puede calcular la diagonal principal de una matriz rectangular?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "En álgebra lineal formal la diagonal principal solo existe en matrices cuadradas donde el número de filas es igual al número de columnas."
          }
        },
        {
          "@type": "Question",
          "name": "¿Cuál es la fórmula para la diagonal secundaria en PSeInt?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "La fórmula de indexación es M[i, N - i + 1], donde i recorre desde 1 hasta N."
          }
        }
      ]
    }
  ]
}
</script></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Algoritmo para Sumar los Elementos de una Matriz en PSeInt: Guía y Diagrama</title>
		<link>https://pseint.org/suma-matriz-pseint/</link>
		
		<dc:creator><![CDATA[El Profe Juan]]></dc:creator>
		<pubDate>Wed, 14 Oct 2026 16:31:07 +0000</pubDate>
				<category><![CDATA[Arreglos y Matrices]]></category>
		<guid isPermaLink="false">https://pseint.org/suma-matriz-pseint/</guid>

					<description><![CDATA[Aprende a sumar los elementos de una matriz en PSeInt con ciclos anidados, suma total, suma de dos matrices y sumas por filas. Incluye diagrama DFD.]]></description>
										<content:encoded><![CDATA[<style>
.entry-title, h1.entry-title {
    max-width: 860px !important;
    margin-left: auto !important;
    margin-right: auto !important;
    text-wrap: balance !important;
    line-height: 1.25 !important;
}
</style>
<article style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1e293b; line-height: 1.8; max-width: 100%;">
<p>    <!-- 1. HEADER METADATA BADGES --></p>
<header style="margin-bottom: 35px;">
<div style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px;">
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #e0f2fe; color: #0369a1; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 700; text-transform: uppercase; line-height: 1.2;">Nivel: Intermedio</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #f1f5f9; color: #475569; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Estructura: Matrices Bidimensionales (Arreglos 2D)</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #fef3c7; color: #b45309; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Patrón: Bucles Anidados Para (Filas x Columnas)</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #ecfdf5; color: #047857; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">PSeInt: Compatible Estricto y Flexible</span>
        </div>
<p>        <!-- BLUF BOX (Bottom Line Up Front) --></p>
<div style="background: #f8fafc; border-left: 5px solid #2563eb; padding: 24px; border-radius: 0 10px 10px 0; box-shadow: 0 2px 4px rgba(0,0,0,0.03);">
<p style="margin: 0 0 12px 0; font-size: 1.12rem; color: #1e293b; font-weight: 600;">
                El <strong>algoritmo para sumar los elementos de una matriz en PSeInt</strong> procesa un arreglo bidimensional mediante <strong>dos bucles anidados</strong>: el ciclo exterior gobierna el índice de filas (<code>i &lt;- 1 Hasta Filas</code>) y el ciclo interior recorre las columnas correspondientes (<code>j &lt;- 1 Hasta Columnas</code>), acumulando cada celda <code>matriz[i, j]</code> en una variable de suma global.
            </p>
<p style="margin: 0; font-size: 0.98rem; color: #475569;">
                <strong>Complejidad algorítmica:</strong> Recorrer una matriz de dimensiones \(F \times C\) exige una complejidad temporal de \(O(F \times C)\), requiriendo tantas operaciones atómicas como celdas totales compongan la cuadrícula, y un consumo de memoria espacial adicional de \(O(1)\) para la acumulación escalar.
            </p>
</p></div>
</header>
<p>    <!-- SECTION 1: THEORY & 2D ARRAYS --></p>
<h2>Fundamentos del Manejo de Matrices Bidimensionales y Ciclos Anidados</h2>
<p>
        A diferencia de los vectores lineales unidimensionales analizados en nuestra guía de <a href="/suma-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">suma de elementos en arreglos</a>, una matriz organiza sus celdas en un plano cartesiano de filas horizontales y columnas verticales. En PSeInt, la definición estricta requiere declarar el tipo y especificar ambas dimensiones separadas por coma:
    </p>
<div style="background: #f1f5f9; border-left: 4px solid #0284c7; padding: 18px; border-radius: 0 8px 8px 0; margin: 20px 0; font-size: 0.95rem; color: #0f172a;">
        <strong>Sintaxis formal de dimensionamiento bidimensional en PSeInt:</strong></p>
<div style="margin-top: 8px; font-family: monospace; font-size: 1.05rem; color: #0369a1; font-weight: 700;">
            Definir matriz Como Entero;<br />
            Dimension matriz[Filas, Columnas];  // Ejemplo: Dimension matriz[3, 3]
        </div>
</p></div>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 18px; margin: 25px 0;">
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #1e40af; font-size: 1.05rem;">1. Coordinación de Índices Anidados</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                El primer subíndice <code>i</code> representa la <strong>fila</strong> activa, mientras que el segundo <code>j</code> designa la <strong>columna</strong>. Reutilizar la misma variable de control en ambos niveles descalibra los punteros y provoca bucles infinitos o desbordamientos.
            </p>
</p></div>
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #047857; font-size: 1.05rem;">2. Tipos de Operaciones de Suma</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                Existen tres variantes habituales: <strong>suma total</strong> (acumulador escalar), <strong>suma de dos matrices</strong> algebraicas (\(C = A + B\)) y <strong>sumas marginales</strong> (vectores independientes para totales por fila y por columna).
            </p>
</p></div>
</p></div>
<p>    <!-- COMPARISON TABLE: 1D VS 2D --></p>
<div style="overflow-x: auto; margin: 25px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.95rem; text-align: left; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
<thead style="background-color: #1e293b; color: #ffffff;">
<tr>
<th style="padding: 12px 16px;">Característica</th>
<th style="padding: 12px 16px;">Vector Unidimensional (1D)</th>
<th style="padding: 12px 16px;">Matriz Bidimensional (2D)</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 16px; font-weight: 600;">Estructura de Índices</td>
<td style="padding: 12px 16px;">1 subíndice: <code>v[i]</code></td>
<td style="padding: 12px 16px; color: #1e40af; font-weight: 600;">2 subíndices: <code>M[i, j]</code> (fila, columna)</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 12px 16px; font-weight: 600;">Ciclos Requeridos para Recorrido</td>
<td style="padding: 12px 16px;">1 bucle <code>Para</code> simple</td>
<td style="padding: 12px 16px; color: #047857; font-weight: 600;">2 bucles <code>Para</code> anidados concéntricos</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 16px; font-weight: 600;">Celdas Totales</td>
<td style="padding: 12px 16px;">\(N\) elementos</td>
<td style="padding: 12px 16px;">\(F \times C\) elementos</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 12px 16px; font-weight: 600;">Complejidad Temporal</td>
<td style="padding: 12px 16px;">\(O(N)\) lineal</td>
<td style="padding: 12px 16px;">\(O(F \times C)\) cuadrática / bilineal</td>
</tr>
</tbody>
</table></div>
<p>    <!-- SECTION 2: EXERCISE 1 (CORE GLOBAL MATRIX SUM) --></p>
<h2>Ejercicio 1 Suma Total de los Elementos de una Matriz</h2>
<p>
        El siguiente algoritmo inicializa una matriz cuadrada de \(3 \times 3\) (9 elementos en total). Mediante dos <a href="/para-hasta-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">bucles Para</a> anidados, acumula la totalidad de las celdas y calcula el promedio global:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Perfil Estricto y Flexible)</span><br />
            <span style="background: #2563eb; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Suma Total 3&#215;3</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo SumaTotalMatriz
    // 1. Declaración estricta de variables y dimensiones
    Definir F, C, i, j, sumaTotal Como Entero
    Definir promedio Como Real
    Definir M Como Entero
    
    F &lt;- 3
    C &lt;- 3
    Dimension M[3, 3]
    
    // 2. Carga de datos de la matriz 3x3
    // Fila 1
    M[1, 1] &lt;- 5;   M[1, 2] &lt;- 8;   M[1, 3] &lt;- 2
    // Fila 2
    M[2, 1] &lt;- 4;   M[2, 2] &lt;- 9;   M[2, 3] &lt;- 7
    // Fila 3
    M[3, 1] &lt;- 1;   M[3, 2] &lt;- 3;   M[3, 3] &lt;- 6
    
    Escribir "=== MATRIZ ORIGINAL 3x3 ==="
    Para i &lt;- 1 Hasta F Con Paso 1 Hacer
        Para j &lt;- 1 Hasta C Con Paso 1 Hacer
            Escribir Sin Saltar M[i, j], "  "
        FinPara
        Escribir "" // Salto de línea por fila
    FinPara
    
    // 3. Inicialización del acumulador
    sumaTotal &lt;- 0
    
    // 4. Recorrido exhaustivo por filas y columnas
    Para i &lt;- 1 Hasta F Con Paso 1 Hacer
        Para j &lt;- 1 Hasta C Con Paso 1 Hacer
            sumaTotal &lt;- sumaTotal + M[i, j]
        FinPara
    FinPara
    
    // 5. Cálculo del promedio y emisión de resultados
    promedio &lt;- sumaTotal / (F * C)
    
    Escribir "--------------------------------------------"
    Escribir "La suma total de todos los elementos es: ", sumaTotal
    Escribir "Cantidad total de celdas evaluadas: ", F * C
    Escribir "El promedio general de la matriz es: ", promedio
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 3: FLOWCHART --></p>
<h2>Diagrama de Flujo de la Suma de Matrices en PSeInt</h2>
<p>
        El diagrama de flujo oficial estandarizado en DFD evidencia la mecánica de los ciclos concéntricos: el bucle interno de columnas finaliza completamente antes de que el ciclo externo avance a la siguiente fila:
    </p>
<figure style="margin: 30px auto; text-align: center; max-width: 780px;">
<div style="background: #ffffff; padding: 16px; border: 1px solid #e2e8f0; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.06);">
            <img decoding="async" src="https://pseint.org/wp-content/uploads/2026/11/suma-matriz-pseint-diagrama-flujo.png" 
                 alt="Diagrama de flujo del algoritmo para sumar una matriz con ciclos anidados en PSeInt" 
                 style="max-width: 100%; height: auto; border-radius: 8px; display: block; margin: 0 auto;" />
        </div><figcaption style="margin-top: 10px; font-size: 0.88rem; color: #64748b; font-style: italic;">
            Figura 1. Diagrama de flujo oficial DFD en PSeInt detallando la doble jerarquía de iteración y la acumulación secuencial celda a celda.<br />
        </figcaption></figure>
<p>    <!-- SECTION 4: TRACE TABLE --></p>
<h2>Prueba de Escritorio Detallada con Matrices Cuadradas y Rectangulares</h2>
<p>
        A continuación se desglosan 5 escenarios críticos de prueba de escritorio para verificar que la suma matricial responda con precisión matemática ante diferentes topologías y signos:
    </p>
<div style="overflow-x: auto; margin: 25px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.9rem; text-align: center; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
<thead style="background-color: #1e293b; color: #ffffff;">
<tr>
<th style="padding: 10px 14px;">Caso / Topología</th>
<th style="padding: 10px 14px;">Filas x Columnas</th>
<th style="padding: 10px 14px;">Valores Matriciales</th>
<th style="padding: 10px 14px;">Celdas Totales</th>
<th style="padding: 10px 14px;">Operación Acumulada</th>
<th style="padding: 10px 14px;">Suma Total</th>
<th style="padding: 10px 14px;">Promedio</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">1. Cuadrada 3&#215;3 Estándar</td>
<td style="padding: 10px 14px;">3 x 3</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.8rem;">[5,8,2; 4,9,7; 1,3,6]</td>
<td style="padding: 10px 14px;">9</td>
<td style="padding: 10px 14px; font-size: 0.82rem;">(5+8+2) + (4+9+7) + (1+3+6)</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">45</td>
<td style="padding: 10px 14px; font-weight: 600;">5.0</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 10px 14px; font-weight: 600;">2. Rectangular 2&#215;3 (F &lt; C)</td>
<td style="padding: 10px 14px;">2 x 3</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.8rem;">[10, 20, 30; 40, 50, 60]</td>
<td style="padding: 10px 14px;">6</td>
<td style="padding: 10px 14px; font-size: 0.82rem;">60 + 150</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">210</td>
<td style="padding: 10px 14px; font-weight: 600;">35.0</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">3. Con Negativos y Ceros</td>
<td style="padding: 10px 14px;">2 x 2</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.8rem;">[-5, 10; 0, -3]</td>
<td style="padding: 10px 14px;">4</td>
<td style="padding: 10px 14px; font-size: 0.82rem;">(-5) + 10 + 0 + (-3)</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">2</td>
<td style="padding: 10px 14px; font-weight: 600;">0.5</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 10px 14px; font-weight: 600;">4. Caso Borde 1&#215;1</td>
<td style="padding: 10px 14px;">1 x 1</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.8rem;">[88]</td>
<td style="padding: 10px 14px;">1</td>
<td style="padding: 10px 14px; font-size: 0.82rem;">88</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">88</td>
<td style="padding: 10px 14px; font-weight: 600;">88.0</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">5. Matriz Diagonal / Identidad</td>
<td style="padding: 10px 14px;">3 x 3</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.8rem;">[1,0,0; 0,1,0; 0,0,1]</td>
<td style="padding: 10px 14px;">9</td>
<td style="padding: 10px 14px; font-size: 0.82rem;">1 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 1</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">3</td>
<td style="padding: 10px 14px; font-weight: 600;">0.333</td>
</tr>
</tbody>
</table></div>
<p>    <!-- SECTION 5: EXERCISE 2 (ALGEBRAIC SUM OF TWO MATRICES C = A + B) --></p>
<h2>Ejercicio 2 Suma Algebraica de Dos Matrices con Matriz Resultante</h2>
<p>
        En el álgebra lineal, sumar dos matrices \(A\) y \(B\) consiste en generar una tercera matriz \(C\) de idénticas dimensiones sumando sus elementos homólogos (\(C_{i,j} = A_{i,j} + B_{i,j}\)):
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Suma Matricial C = A + B)</span><br />
            <span style="background: #059669; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Álgebra Lineal 2D</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo SumarDosMatrices
    Definir F, C, i, j Como Entero
    Definir MatrizA, MatrizB, MatrizC Como Entero
    
    F &lt;- 2
    C &lt;- 3
    Dimension MatrizA[2, 3], MatrizB[2, 3], MatrizC[2, 3]
    
    // Carga de Matriz A
    MatrizA[1, 1] &lt;- 1; MatrizA[1, 2] &lt;- 2; MatrizA[1, 3] &lt;- 3
    MatrizA[2, 1] &lt;- 4; MatrizA[2, 2] &lt;- 5; MatrizA[2, 3] &lt;- 6
    
    // Carga de Matriz B
    MatrizB[1, 1] &lt;- 7; MatrizB[1, 2] &lt;- 8; MatrizB[1, 3] &lt;- 9
    MatrizB[2, 1] &lt;- 1; MatrizB[2, 2] &lt;- 2; MatrizB[2, 3] &lt;- 3
    
    // Proceso de suma posición por posición
    Para i &lt;- 1 Hasta F Con Paso 1 Hacer
        Para j &lt;- 1 Hasta C Con Paso 1 Hacer
            MatrizC[i, j] &lt;- MatrizA[i, j] + MatrizB[i, j]
        FinPara
    FinPara
    
    // Impresión formateada de la Matriz C resultante
    Escribir "=== MATRIZ C RESULTANTE (A + B) ==="
    Para i &lt;- 1 Hasta F Con Paso 1 Hacer
        Escribir Sin Saltar "Fila ", i, ": [ "
        Para j &lt;- 1 Hasta C Con Paso 1 Hacer
            Escribir Sin Saltar MatrizC[i, j], " "
        FinPara
        Escribir "]"
    FinPara
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 6: EXERCISE 3 (ROW AND COLUMN SUMS) --></p>
<h2>Ejercicio 3 Cálculo Simultáneo de la Suma por Filas y por Columnas</h2>
<p>
        En análisis contables y hojas de cálculo, se requiere frecuentemente calcular los subtotales horizontales (sumas de cada fila) y los subtotales verticales (sumas de cada columna), almacenándolos en vectores complementarios:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Subtotales Filas y Columnas)</span><br />
            <span style="background: #9333ea; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Subtotales Marginales</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo SumaFilasYColumnas
    Definir F, C, i, j Como Entero
    Definir tabla, sumaFila, sumaColumna Como Entero
    
    F &lt;- 3
    C &lt;- 3
    Dimension tabla[3, 3], sumaFila[3], sumaColumna[3]
    
    // Inicialización de la tabla con valores
    tabla[1, 1] &lt;- 10; tabla[1, 2] &lt;- 20; tabla[1, 3] &lt;- 30
    tabla[2, 1] &lt;- 5;  tabla[2, 2] &lt;- 15; tabla[2, 3] &lt;- 25
    tabla[3, 1] &lt;- 8;  tabla[3, 2] &lt;- 12; tabla[3, 3] &lt;- 16
    
    // 1. Cálculo de las sumas por fila
    Para i &lt;- 1 Hasta F Con Paso 1 Hacer
        sumaFila[i] &lt;- 0
        Para j &lt;- 1 Hasta C Con Paso 1 Hacer
            sumaFila[i] &lt;- sumaFila[i] + tabla[i, j]
        FinPara
    FinPara
    
    // 2. Cálculo de las sumas por columna (inversión de orden de bucles)
    Para j &lt;- 1 Hasta C Con Paso 1 Hacer
        sumaColumna[j] &lt;- 0
        Para i &lt;- 1 Hasta F Con Paso 1 Hacer
            sumaColumna[j] &lt;- sumaColumna[j] + tabla[i, j]
        FinPara
    FinPara
    
    // 3. Emisión de reportes
    Escribir "=== SUMAS POR FILA ==="
    Para i &lt;- 1 Hasta F Con Paso 1 Hacer
        Escribir "Total Fila [", i, "]: ", sumaFila[i]
    FinPara
    
    Escribir "--------------------------------------------"
    Escribir "=== SUMAS POR COLUMNA ==="
    Para j &lt;- 1 Hasta C Con Paso 1 Hacer
        Escribir "Total Columna [", j, "]: ", sumaColumna[j]
    FinPara
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 7: EXERCISE 4 (MODULARIZATION WITH SUBPROCESS) --></p>
<h2>Ejercicio 4 Modularización con Subprocesos para Operaciones con Matrices</h2>
<p>
        Para mantener una arquitectura de software limpia y desacoplada, se implementa un <a href="/subproceso-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Subproceso en PSeInt</a> que recibe la matriz y sus cotas, calculando y retornando la sumatoria total:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Subproceso Modular de Suma)</span><br />
            <span style="background: #0891b2; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Función Modular</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">// Subproceso que calcula la sumatoria de cualquier matriz
Funcion total &lt;- CalcularSumaMatriz(mat Por Referencia, filas, columnas)
    Definir total, r, c Como Entero
    total &lt;- 0
    Para r &lt;- 1 Hasta filas Con Paso 1 Hacer
        Para c &lt;- 1 Hasta columnas Con Paso 1 Hacer
            total &lt;- total + mat[r, c]
        FinPara
    FinPara
FinFuncion

Algoritmo PrincipalMatrizModular
    Definir nFil, nCol, resultadoSuma Como Entero
    Definir datosMatriz Como Entero
    
    nFil &lt;- 2
    nCol &lt;- 2
    Dimension datosMatriz[2, 2]
    
    datosMatriz[1, 1] &lt;- 50;  datosMatriz[1, 2] &lt;- 25
    datosMatriz[2, 1] &lt;- 15;  datosMatriz[2, 2] &lt;- 10
    
    resultadoSuma &lt;- CalcularSumaMatriz(datosMatriz, nFil, nCol)
    
    Escribir "=== REPORTE MODULAR ==="
    Escribir "La función retornó una suma total de: ", resultadoSuma
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 8: COMMON MISTAKES --></p>
<h2>Errores Comunes al Trabajar con Matrices en PSeInt</h2>
<p>
        La introducción de una segunda dimensión suele generar confusiones en estudiantes principiantes. Los fallos más usuales son:
    </p>
<div style="display: flex; flex-direction: column; gap: 16px; margin: 25px 0;">
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">1. Confundir el orden de filas y columnas [i, j]</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                En una matriz rectangular de \(2 \times 5\), escribir <code>matriz[j, i]</code> en vez de <code>matriz[i, j]</code> intentará acceder a la fila 5 cuando solo existen 2, provocando el <a href="/error-303-pseint/" style="color: #9f1239; text-decoration: underline; font-weight: 700;">Error 303: Subíndice fuera de rango</a>. Recuerde siempre: primer número fila, segundo columna.
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">2. Intentar sumar matrices con dimensiones incompatibles</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Para la suma algebraica de dos matrices (\(C = A + B\)), es una condición matemática inquebrantable que ambas matrices tengan exactamente la misma cantidad de filas y de columnas. Sumar una matriz \(2 \times 3\) con una \(3 \times 2\) es una operación indefinida.
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">3. Reutilizar la misma variable de control en ciclos anidados</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Escribir <code>Para i &lt;- 1 Hasta F</code> y dentro colocar otro <code>Para i &lt;- 1 Hasta C</code> destruye el valor del contador externo, originando un bucle infinito o finalizaciones prematuras. Emplee siempre variables distintas (<code>i</code> para filas y <code>j</code> para columnas).
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">4. Olvidar reiniciar el acumulador en sumas parciales</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Al calcular la suma de cada fila por separado, la asignación <code>sumaFila &lt;- 0</code> debe ubicarse dentro del bucle de filas y antes de iniciar el bucle de columnas. Colocarla fuera acumulará las sumas de filas anteriores. Revise más problemas en la <a href="/errores-comunes-pseint/" style="color: #9f1239; text-decoration: underline; font-weight: 700;">guía completa de errores en PSeInt</a>.
            </p>
</p></div>
</p></div>
<p>    <!-- SECTION 9: FAQ --></p>
<h2>Preguntas Frecuentes sobre Matrices y Arreglos Bidimensionales en PSeInt</h2>
<div style="display: flex; flex-direction: column; gap: 14px; margin: 25px 0;">
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿PSeInt admite matrices de más de dos dimensiones?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                Sí, PSeInt permite definir arreglos multidimensionales (de 3 o más dimensiones) simplemente separando las dimensiones por comas con <code>Dimension cubo[X, Y, Z]</code>, aunque en la enseñanza habitual se trabaja predominantemente con vectores 1D y matrices 2D.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Cómo se vincula este ejercicio con la tabla de multiplicar del 1 al 10?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                El patrón de doble iteración es idéntico al empleado en las <a href="/tablas-multiplicar-1-10-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">tablas de multiplicar con bucles anidados</a>, con la diferencia de que en las matrices cada producto u operación se almacena en una celda indexada en memoria.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Cuál es la diferencia entre sumar por filas y sumar por columnas?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                Para sumar por filas, el bucle externo itera sobre <code>i</code> y el interno sobre <code>j</code>. Para sumar por columnas, se invierte la jerarquía: el bucle externo recorre <code>j</code> (columnas) y el interno <code>i</code> (filas), permitiendo totalizar cada columna de forma continua.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Cómo se inicializa una matriz dinámica con valores leídos del teclado?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                Se colocan los mismos dos ciclos anidados y dentro se ejecuta la instrucción <code>Leer matriz[i, j]</code>, solicitando sucesivamente al usuario los valores de cada coordenada matricial.
            </p>
</p></div>
</p></div>
<p>    <!-- CTA & INTERNAL NAVIGATION --></p>
<div style="background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); color: #ffffff; padding: 32px 24px; border-radius: 12px; margin: 40px 0; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.12);">
<h3 style="color: #ffffff; margin-top: 0; font-size: 1.35rem; margin-bottom: 12px;">Continúa Fortaleciendo tus Habilidades en Algoritmia</h3>
<p style="color: #94a3b8; font-size: 1rem; max-width: 680px; margin: 0 auto 24px auto; line-height: 1.6;">
            Explora más algoritmos resueltos paso a paso con diagramas de flujo interactivos, pruebas de escritorio y explicaciones detalladas para todos los niveles formativos.
        </p>
<div><a href="/ejercicios-resueltos/" style="display: inline-flex; align-items: center; justify-content: center; line-height: 1.2; background-color: #2563eb; color: #ffffff; padding: 12px 28px; border-radius: 8px; text-decoration: none; font-weight: 700; font-size: 1rem; transition: background 0.2s ease-in-out;">Explorar Catálogo de Ejercicios Resueltos</a></div>
</p></div>
</article>
<p><!-- JSON-LD SCHEMA METADATA --><br />
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "TechArticle",
      "headline": "Algoritmo para Sumar los Elementos de una Matriz en PSeInt: Guía y Diagrama",
      "description": "Aprende a sumar los elementos de una matriz en PSeInt con ciclos anidados, suma total, suma de dos matrices y sumas por filas. Incluye diagrama DFD.",
      "proficiencyLevel": "Intermediate",
      "inLanguage": "es",
      "author": {
        "@type": "Organization",
        "name": "PSeInt.org"
      }
    },
    {
      "@type": "HowTo",
      "name": "Cómo sumar los elementos de una matriz en PSeInt con bucles anidados",
      "description": "Procedimiento paso a paso para recorrer y sumar una estructura bidimensional de filas y columnas en PSeInt.",
      "step": [
        {
          "@type": "HowToStep",
          "name": "Declarar variables y dimensionar la matriz",
          "text": "Definir las variables de control i, j, la matriz con Dimension M[Filas, Columnas] y el acumulador de suma."
        },
        {
          "@type": "HowToStep",
          "name": "Inicializar el acumulador en cero",
          "text": "Asignar 0 a la variable sumaTotal antes de entrar a la estructura iterativa."
        },
        {
          "@type": "HowToStep",
          "name": "Estructurar los bucles anidados de filas y columnas",
          "text": "Crear un bucle Para externo para las filas i y un bucle Para interno para las columnas j."
        },
        {
          "@type": "HowToStep",
          "name": "Acumular y presentar el resultado",
          "text": "Ejecutar sumaTotal <- sumaTotal + M[i, j] en cada iteración y mostrar el gran total al finalizar."
        }
      ]
    },
    {
      "@type": "FAQPage",
      "mainEntity": [
        {
          "@type": "Question",
          "name": "¿Cuál es la complejidad algorítmica de sumar una matriz en PSeInt?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "La complejidad temporal es O(F * C), directamente proporcional a la cantidad total de celdas que componen la cuadrícula."
          }
        },
        {
          "@type": "Question",
          "name": "¿Qué condición deben cumplir dos matrices para poder sumarse?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Deben tener obligatoriamente la misma dimensión exacta (igual cantidad de filas e igual cantidad de columnas)."
          }
        },
        {
          "@type": "Question",
          "name": "¿Por qué es obligatorio usar variables distintas en los ciclos anidados?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Porque reutilizar la misma variable sobrescribiría el índice de fila exterior, rompiendo la lógica y causando bucles infinitos."
          }
        }
      ]
    }
  ]
}
</script></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Algoritmo para Invertir un Arreglo en PSeInt: Guía y Diagrama</title>
		<link>https://pseint.org/invertir-arreglo-pseint/</link>
		
		<dc:creator><![CDATA[El Profe Juan]]></dc:creator>
		<pubDate>Wed, 14 Oct 2026 16:30:11 +0000</pubDate>
				<category><![CDATA[Arreglos y Matrices]]></category>
		<guid isPermaLink="false">https://pseint.org/invertir-arreglo-pseint/</guid>

					<description><![CDATA[Aprende a invertir un arreglo en PSeInt in-situ mediante intercambio swap (O(1) memoria) y con vector auxiliar. Incluye diagrama DFD y prueba de escritorio.]]></description>
										<content:encoded><![CDATA[<style>
.entry-title, h1.entry-title {
    max-width: 860px !important;
    margin-left: auto !important;
    margin-right: auto !important;
    text-wrap: balance !important;
    line-height: 1.25 !important;
}
</style>
<article style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1e293b; line-height: 1.8; max-width: 100%;">
<p>    <!-- 1. HEADER METADATA BADGES --></p>
<header style="margin-bottom: 35px;">
<div style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px;">
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #e0f2fe; color: #0369a1; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 700; text-transform: uppercase; line-height: 1.2;">Nivel: Básico &#8211; Intermedio</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #f1f5f9; color: #475569; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Técnica: Intercambio In Situ (Swap)</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #fef3c7; color: #b45309; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Memoria Auxiliar: O(1) Constante</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #ecfdf5; color: #047857; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">PSeInt: Compatible Estricto y Flexible</span>
        </div>
<p>        <!-- BLUF BOX (Bottom Line Up Front) --></p>
<div style="background: #f8fafc; border-left: 5px solid #2563eb; padding: 24px; border-radius: 0 10px 10px 0; box-shadow: 0 2px 4px rgba(0,0,0,0.03);">
<p style="margin: 0 0 12px 0; font-size: 1.12rem; color: #1e293b; font-weight: 600;">
                El <strong>algoritmo para invertir un arreglo en PSeInt</strong> reorganiza el orden de sus elementos de modo que el primer valor pasa al último casillero y viceversa. La estrategia óptima es el <strong>intercambio in-situ (en el mismo espacio)</strong>: se recorre únicamente hasta la mitad entera del vector (<code>trunc(N / 2)</code>) y se permutan los extremos simétricos (<code>v[i]</code> con <code>v[N - i + 1]</code>) mediante una variable temporal <code>aux</code>.
            </p>
<p style="margin: 0; font-size: 0.98rem; color: #475569;">
                <strong>Regla de oro de la simetría:</strong> Si el bucle recorre el arreglo completo hasta \(N\) en lugar de detenerse en \(\lfloor N / 2 \rfloor\), el algoritmo invertirá los valores en la primera mitad y los volverá a intercambiar en la segunda mitad, dejando el arreglo exactamente en su estado original (doble inversión destructiva).
            </p>
</p></div>
</header>
<p>    <!-- SECTION 1: THEORY & SWAP PATTERN --></p>
<h2>Fundamentos del Algoritmo de Inversión y el Patrón de Intercambio Swap</h2>
<p>
        La inversión de vectores es una operación estructural clásica en ciencias de la computación. En pseudocódigo estructurado existen dos formas conceptuales de resolver este desafío, diferenciadas por el consumo de memoria:
    </p>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 18px; margin: 25px 0;">
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #1e40af; font-size: 1.05rem;">1. Inversión In Situ (Recomendada)</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                Modifica el arreglo original sin crear copias. Emplea solo una variable auxiliar de intercambio. <strong>Complejidad temporal:</strong> \(O(N/2) = O(N)\). <strong>Complejidad espacial:</strong> \(O(1)\) memoria constante.
            </p>
</p></div>
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #047857; font-size: 1.05rem;">2. Inversión con Vector Auxiliar</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                Crea un segundo arreglo de tamaño \(N\) y copia los valores en sentido inverso (<code>invertido[i] &lt;- origen[N - i + 1]</code>). Más intuitivo pero duplica el consumo de memoria (\(O(N)\) espacio adicional).
            </p>
</p></div>
</p></div>
<p>    <!-- COMPARISON TABLE: IN-PLACE VS AUXILIARY --></p>
<div style="overflow-x: auto; margin: 25px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.95rem; text-align: left; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
<thead style="background-color: #1e293b; color: #ffffff;">
<tr>
<th style="padding: 12px 16px;">Criterio Técnico</th>
<th style="padding: 12px 16px;">Inversión In Situ (Swap)</th>
<th style="padding: 12px 16px;">Inversión con Vector Secundario</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 16px; font-weight: 600;">Consumo de Memoria RAM</td>
<td style="padding: 12px 16px; color: #166534; font-weight: 600;">Óptimo \(O(1)\) (1 variable escalar aux)</td>
<td style="padding: 12px 16px; color: #b45309; font-weight: 600;">\(O(N)\) (duplica la memoria requerida)</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 12px 16px; font-weight: 600;">Iteraciones del Ciclo</td>
<td style="padding: 12px 16px;">Exactamente \(\lfloor N / 2 \rfloor\) intercambios</td>
<td style="padding: 12px 16px;">Exactamente \(N\) asignaciones directas</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 16px; font-weight: 600;">Preservación del Arreglo Inicial</td>
<td style="padding: 12px 16px;">Se sobrescribe el orden de origen</td>
<td style="padding: 12px 16px; color: #166534; font-weight: 600;">Conserva el vector original intacto</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 12px 16px; font-weight: 600;">Fórmula del Índice Espejo</td>
<td style="padding: 12px 16px; font-family: monospace;">espejo = N &#8211; i + 1</td>
<td style="padding: 12px 16px; font-family: monospace;">espejo = N &#8211; i + 1</td>
</tr>
</tbody>
</table></div>
<p>    <!-- SECTION 2: EXERCISE 1 (CORE IN-PLACE SWAP WITH FOR LOOP) --></p>
<h2>Ejercicio 1 Inversión In Situ Mediante Intercambio y Mitad del Arreglo</h2>
<p>
        El siguiente algoritmo ejemplifica la técnica profesional in-situ. Recorre un arreglo de 6 enteros con el <a href="/para-hasta-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">bucle Para</a> hasta <code>trunc(N / 2)</code>, realizando la clásica maniobra de tres pasos para intercambiar sin pérdida de datos:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Perfil Estricto y Flexible)</span><br />
            <span style="background: #2563eb; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">In Situ Óptimo</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo InvertirArregloInSitu
    // 1. Declaración formal de variables y arreglo
    Definir N, i, aux, limite, posOpuesta Como Entero
    Definir vector Como Entero
    
    N &lt;- 6
    Dimension vector[6]
    
    // 2. Asignación de valores de prueba
    vector[1] &lt;- 10
    vector[2] &lt;- 20
    vector[3] &lt;- 30
    vector[4] &lt;- 40
    vector[5] &lt;- 50
    vector[6] &lt;- 60
    
    Escribir "=== ARREGLO ORIGINAL ==="
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        Escribir Sin Saltar vector[i], " "
    FinPara
    Escribir ""
    
    // 3. Cálculo de la cota media para evitar deshacer el swap
    limite &lt;- trunc(N / 2)
    
    // 4. Proceso de intercambio de extremos
    Para i &lt;- 1 Hasta limite Con Paso 1 Hacer
        posOpuesta &lt;- N - i + 1
        
        // Bloque canónico Swap con variable auxiliar
        aux &lt;- vector[i]
        vector[i] &lt;- vector[posOpuesta]
        vector[posOpuesta] &lt;- aux
    FinPara
    
    // 5. Presentación del arreglo invertido
    Escribir "--------------------------------------------"
    Escribir "=== ARREGLO INVERTIDO (IN SITU) ==="
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        Escribir Sin Saltar vector[i], " "
    FinPara
    Escribir ""
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 3: FLOWCHART --></p>
<h2>Diagrama de Flujo del Algoritmo para Invertir un Arreglo</h2>
<p>
        El diagrama de flujo en formato DFD de PSeInt refleja gráficamente el cálculo previo del límite de simetría y el cuerpo del bucle con la asignación cíclica de la variable <code>aux</code>:
    </p>
<figure style="margin: 30px auto; text-align: center; max-width: 780px;">
<div style="background: #ffffff; padding: 16px; border: 1px solid #e2e8f0; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.06);">
            <img decoding="async" src="https://pseint.org/wp-content/uploads/2026/11/invertir-arreglo-pseint-diagrama-flujo.png" 
                 alt="Diagrama de flujo del algoritmo para invertir un arreglo in situ en PSeInt" 
                 style="max-width: 100%; height: auto; border-radius: 8px; display: block; margin: 0 auto;" />
        </div><figcaption style="margin-top: 10px; font-size: 0.88rem; color: #64748b; font-style: italic;">
            Figura 1. Diagrama de flujo oficial DFD en PSeInt mostrando el recorrido hasta trunc(N/2) y la secuencia de permuta simétrica en el bloque de proceso.<br />
        </figcaption></figure>
<p>    <!-- SECTION 4: TRACE TABLE --></p>
<h2>Prueba de Escritorio Detallada con Arreglos Pares e Impares</h2>
<p>
        La validez de este algoritmo se comprueba examinando cómo reacciona ante dimensiones pares (donde cada celda tiene pareja) y dimensiones impares (donde el centro permanece inmóvil):
    </p>
<div style="overflow-x: auto; margin: 25px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.9rem; text-align: center; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
<thead style="background-color: #1e293b; color: #ffffff;">
<tr>
<th style="padding: 10px 14px;">Escenario</th>
<th style="padding: 10px 14px;">Tamaño (N)</th>
<th style="padding: 10px 14px;">Límite trunc(N/2)</th>
<th style="padding: 10px 14px;">Iteración (i)</th>
<th style="padding: 10px 14px;">Celdas Intercambiadas</th>
<th style="padding: 10px 14px;">Estado del Vector</th>
<th style="padding: 10px 14px;">Observación Técnica</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;" rowspan="3">1. Arreglo Par<br /><code>[10, 20, 30, 40, 50, 60]</code></td>
<td style="padding: 10px 14px;" rowspan="3">6</td>
<td style="padding: 10px 14px;" rowspan="3">3</td>
<td style="padding: 10px 14px;">i = 1</td>
<td style="padding: 10px 14px; font-family: monospace;">v[1] &lt;-&gt; v[6]</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">[60, 20, 30, 40, 50, 10]</td>
<td style="padding: 10px 14px; font-size: 0.82rem;">10 permuta con 60</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px;">i = 2</td>
<td style="padding: 10px 14px; font-family: monospace;">v[2] &lt;-&gt; v[5]</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">[60, 50, 30, 40, 20, 10]</td>
<td style="padding: 10px 14px; font-size: 0.82rem;">20 permuta con 50</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px;">i = 3</td>
<td style="padding: 10px 14px; font-family: monospace;">v[3] &lt;-&gt; v[4]</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem; font-weight: 700; color: #166534;">[60, 50, 40, 30, 20, 10]</td>
<td style="padding: 10px 14px; font-size: 0.82rem; color: #166534;">Finaliza ciclo exactamente</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 10px 14px; font-weight: 600;" rowspan="2">2. Arreglo Impar<br /><code>[1, 2, 3, 4, 5]</code></td>
<td style="padding: 10px 14px;" rowspan="2">5</td>
<td style="padding: 10px 14px;" rowspan="2">2</td>
<td style="padding: 10px 14px;">i = 1</td>
<td style="padding: 10px 14px; font-family: monospace;">v[1] &lt;-&gt; v[5]</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">[5, 2, 3, 4, 1]</td>
<td style="padding: 10px 14px; font-size: 0.82rem;">Extremos permutados</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 10px 14px;">i = 2</td>
<td style="padding: 10px 14px; font-family: monospace;">v[2] &lt;-&gt; v[4]</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem; font-weight: 700; color: #166534;">[5, 4, 3, 2, 1]</td>
<td style="padding: 10px 14px; font-size: 0.82rem; color: #166534;">El centro (3) queda inmóvil</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">3. Arreglo Capicúa<br /><code>[7, 8, 9, 8, 7]</code></td>
<td style="padding: 10px 14px;">5</td>
<td style="padding: 10px 14px;">2</td>
<td style="padding: 10px 14px;">i = 1, 2</td>
<td style="padding: 10px 14px; font-family: monospace;">Permutas simétricas</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">[7, 8, 9, 8, 7]</td>
<td style="padding: 10px 14px; font-size: 0.82rem;">Palíndromo: idéntico resultado</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 10px 14px; font-weight: 600;">4. Caso Unitario Borde<br /><code>[99]</code></td>
<td style="padding: 10px 14px;">1</td>
<td style="padding: 10px 14px;">0</td>
<td style="padding: 10px 14px;">No entra al ciclo</td>
<td style="padding: 10px 14px; color: #64748b;">Ninguna</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">[99]</td>
<td style="padding: 10px 14px; font-size: 0.82rem; color: #166534;">Correcto: 1 elemento no cambia</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">5. Dos Elementos<br /><code>[100, 200]</code></td>
<td style="padding: 10px 14px;">2</td>
<td style="padding: 10px 14px;">1</td>
<td style="padding: 10px 14px;">i = 1</td>
<td style="padding: 10px 14px; font-family: monospace;">v[1] &lt;-&gt; v[2]</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem; font-weight: 700; color: #166534;">[200, 100]</td>
<td style="padding: 10px 14px; font-size: 0.82rem; color: #166534;">Permuta única perfecta</td>
</tr>
</tbody>
</table></div>
<p>    <!-- SECTION 5: EXERCISE 2 (AUXILIARY ARRAY) --></p>
<h2>Ejercicio 2 Inversión Mediante Arreglo Auxiliar Secundario</h2>
<p>
        Si el enunciado de su trabajo o práctica exige <strong>preservar intacto el arreglo de origen</strong> para operaciones posteriores (por ejemplo, para calcular la diferencia entre ambos o para auditar datos), se debe instanciar un segundo vector receptor:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Preservación del Arreglo Original)</span><br />
            <span style="background: #059669; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Vector Secundario</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo InvertirConArregloAuxiliar
    Definir N, i Como Entero
    Definir origen, invertido Como Entero
    
    N &lt;- 5
    Dimension origen[5], invertido[5]
    
    // Carga de datos iniciales
    origen[1] &lt;- 15
    origen[2] &lt;- 28
    origen[3] &lt;- 34
    origen[4] &lt;- 42
    origen[5] &lt;- 59
    
    // Asignación invertida recorriendo N elementos
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        invertido[i] &lt;- origen[N - i + 1]
    FinPara
    
    Escribir "=== MATRIZ ORIGINAL INTACTA ==="
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        Escribir Sin Saltar origen[i], " "
    FinPara
    Escribir ""
    
    Escribir "=== NUEVO VECTOR INVERTIDO ==="
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        Escribir Sin Saltar invertido[i], " "
    FinPara
    Escribir ""
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 6: EXERCISE 3 (TWO POINTERS WITH WHILE LOOP) --></p>
<h2>Ejercicio 3 Inversión Dinámica con Dos Punteros y Bucle Mientras</h2>
<p>
        El patrón de <strong>dos punteros (Two Pointers)</strong> es uno de los algoritmos más valorados en entrevistas de programación y pruebas de algoritmia. Consiste en definir un puntero inicial <code>izquierda &lt;- 1</code> y un puntero final <code>derecha &lt;- N</code> que avanzan hacia el centro con el <a href="/mientras-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">bucle Mientras</a>:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Patrón Dos Punteros)</span><br />
            <span style="background: #9333ea; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Dos Punteros</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo InversionDosPunteros
    Definir N, izq, der, temporal, k Como Entero
    Definir datos Como Entero
    
    N &lt;- 7
    Dimension datos[7]
    datos[1] &lt;- 5
    datos[2] &lt;- 12
    datos[3] &lt;- 8
    datos[4] &lt;- 20
    datos[5] &lt;- 33
    datos[6] &lt;- 17
    datos[7] &lt;- 49
    
    // Punteros a los extremos del vector
    izq &lt;- 1
    der &lt;- N
    
    // Se cruzan exactamente en el centro matemático
    Mientras izq &lt; der Hacer
        temporal &lt;- datos[izq]
        datos[izq] &lt;- datos[der]
        datos[der] &lt;- temporal
        
        // Desplazamiento convergente
        izq &lt;- izq + 1
        der &lt;- der - 1
    FinMientras
    
    Escribir "=== VECTOR INVERTIDO MEDIANTE DOS PUNTEROS ==="
    Para k &lt;- 1 Hasta N Con Paso 1 Hacer
        Escribir Sin Saltar datos[k], " "
    FinPara
    Escribir ""
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 7: EXERCISE 4 (MODULARIZATION WITH SUBPROCESS) --></p>
<h2>Ejercicio 4 Modularización con Subprocesos para Invertir Arreglos</h2>
<p>
        Para mantener el código estructurado y reutilizable en proyectos de gran envergadura, el procedimiento de inversión debe aislarse en un <a href="/subproceso-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Subproceso en PSeInt</a> que recibe el arreglo <code>Por Referencia</code>:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Subproceso Por Referencia)</span><br />
            <span style="background: #0891b2; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Modular</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">// Subproceso modular que invierte cualquier vector in-situ
SubProceso InvertirVectorModular(arr Por Referencia, total)
    Definir p, fin, cambio Como Entero
    fin &lt;- trunc(total / 2)
    Para p &lt;- 1 Hasta fin Con Paso 1 Hacer
        cambio &lt;- arr[p]
        arr[p] &lt;- arr[total - p + 1]
        arr[total - p + 1] &lt;- cambio
    FinPara
FinSubProceso

Algoritmo PrincipalInversionModular
    Definir tam, idx Como Entero
    Definir miArreglo Como Entero
    
    tam &lt;- 5
    Dimension miArreglo[5]
    miArreglo[1] &lt;- 100
    miArreglo[2] &lt;- 200
    miArreglo[3] &lt;- 300
    miArreglo[4] &lt;- 400
    miArreglo[5] &lt;- 500
    
    Escribir "Invocando subproceso de inversión..."
    InvertirVectorModular(miArreglo, tam)
    
    Escribir "=== RESULTADO POST-SUBPROCESO ==="
    Para idx &lt;- 1 Hasta tam Con Paso 1 Hacer
        Escribir Sin Saltar miArreglo[idx], " "
    FinPara
    Escribir ""
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 8: COMMON MISTAKES --></p>
<h2>Errores Comunes al Invertir Arreglos en PSeInt</h2>
<p>
        Al codificar algoritmos de inversión y permutación, existen errores de concepto característicos que impiden el funcionamiento esperado:
    </p>
<div style="display: flex; flex-direction: column; gap: 16px; margin: 25px 0;">
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">1. El error del bucle completo (Doble inversión neutralizadora)</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Iterar desde <code>1 Hasta N</code> en lugar de <code>1 Hasta trunc(N / 2)</code> provoca que al llegar a la segunda mitad del vector, el algoritmo vuelva a intercambiar los elementos ya permutados, devolviendo el vector exactamente a su posición inicial sin avisar de ningún error.
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">2. Intercambio directo sin variable temporal (Pérdida de datos)</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Escribir <code>vector[i] &lt;- vector[N - i + 1]</code> sin guardar previamente <code>aux &lt;- vector[i]</code> destruye el valor original de la posición izquierda, clonando el valor derecho en ambos extremos.
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">3. Desfase de un elemento en el índice simétrico (Error 303)</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                En sistemas con base 1 como PSeInt, la fórmula de la posición simétrica es obligatoriamente <code>N - i + 1</code>. Escribir <code>N - i</code> ocasionará que cuando <code>i = N</code> (o en límites) se acceda a la posición 0, disparando el <a href="/error-303-pseint/" style="color: #9f1239; text-decoration: underline; font-weight: 700;">Error 303: Subíndice fuera de rango</a>.
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">4. Olvidar pasar el arreglo Por Referencia</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                En subprocesos, si se omite la palabra clave <code>Por Referencia</code>, PSeInt pasará una copia local del vector y los cambios se esfumarán al terminar la función. Consulte más precauciones en la <a href="/errores-comunes-pseint/" style="color: #9f1239; text-decoration: underline; font-weight: 700;">guía de errores frecuentes en PSeInt</a>.
            </p>
</p></div>
</p></div>
<p>    <!-- SECTION 9: FAQ --></p>
<h2>Preguntas Frecuentes sobre Inversión de Vectores en PSeInt</h2>
<div style="display: flex; flex-direction: column; gap: 14px; margin: 25px 0;">
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Por qué se usa la función trunc() al calcular la mitad del tamaño?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                Si el tamaño del vector es impar (por ejemplo, \(N = 5\)), la división \(5 / 2 = 2.5\) produce un número no entero. El bucle <code>Para</code> requiere límites enteros; al aplicar <code>trunc(2.5)</code> obtenemos 2, garantizando exactamente 2 intercambios y dejando el elemento 3 central inalterado.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Es lo mismo invertir un arreglo que ordenarlo de forma descendente?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                No. Invertir simplemente cambia el sentido de las posiciones (el último pasa al primero) sin importar las magnitudes numéricas. Ordenar requiere comparar magnitudes para colocarlos de mayor a menor.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Cómo se conecta este ejercicio con los otros algoritmos de arreglos?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                La inversión in-situ culmina la serie de manipulación de arreglos unidimensionales junto con la <a href="/buscar-en-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">búsqueda lineal</a>, el <a href="/contar-pares-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">conteo de números pares</a>, el <a href="/mayor-menor-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">mayor y menor valor</a> y la <a href="/suma-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">suma de elementos de un arreglo</a>.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Se puede aplicar este algoritmo a cadenas de texto en PSeInt?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                Sí. Se puede descomponer la palabra en un arreglo de caracteres (utilizando la función <code>SubCadena</code>) y aplicar la misma lógica de inversión in-situ o acumular los caracteres en sentido decreciente con un ciclo con paso -1.
            </p>
</p></div>
</p></div>
<p>    <!-- CTA & INTERNAL NAVIGATION --></p>
<div style="background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); color: #ffffff; padding: 32px 24px; border-radius: 12px; margin: 40px 0; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.12);">
<h3 style="color: #ffffff; margin-top: 0; font-size: 1.35rem; margin-bottom: 12px;">Continúa Fortaleciendo tus Habilidades en Algoritmia</h3>
<p style="color: #94a3b8; font-size: 1rem; max-width: 680px; margin: 0 auto 24px auto; line-height: 1.6;">
            Explora más algoritmos resueltos paso a paso con diagramas de flujo interactivos, pruebas de escritorio y explicaciones detalladas para todos los niveles formativos.
        </p>
<div><a href="/ejercicios-resueltos/" style="display: inline-flex; align-items: center; justify-content: center; line-height: 1.2; background-color: #2563eb; color: #ffffff; padding: 12px 28px; border-radius: 8px; text-decoration: none; font-weight: 700; font-size: 1rem; transition: background 0.2s ease-in-out;">Explorar Catálogo de Ejercicios Resueltos</a></div>
</p></div>
</article>
<p><!-- JSON-LD SCHEMA METADATA --><br />
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "TechArticle",
      "headline": "Algoritmo para Invertir un Arreglo en PSeInt: Guía y Diagrama",
      "description": "Aprende a invertir un arreglo en PSeInt in-situ mediante intercambio swap (O(1) memoria) y con vector auxiliar. Incluye diagrama DFD y prueba de escritorio.",
      "proficiencyLevel": "Beginner",
      "inLanguage": "es",
      "author": {
        "@type": "Organization",
        "name": "PSeInt.org"
      }
    },
    {
      "@type": "HowTo",
      "name": "Cómo invertir un arreglo in-situ en PSeInt mediante intercambio",
      "description": "Procedimiento paso a paso para permutar los extremos simétricos de un arreglo hasta la mitad entera trunc(N/2) con una variable temporal.",
      "step": [
        {
          "@type": "HowToStep",
          "name": "Dimensionar el arreglo y cargar los elementos",
          "text": "Declarar las variables enteras, dimensionar el vector con tamaño N y poblarlo con los valores iniciales."
        },
        {
          "@type": "HowToStep",
          "name": "Calcular el límite central con trunc(N/2)",
          "text": "Establecer la cota máxima del bucle Para en la mitad entera para evitar deshacer los cambios en la segunda mitad."
        },
        {
          "@type": "HowToStep",
          "name": "Ejecutar el intercambio swap de extremos",
          "text": "Para cada i, guardar vector[i] en aux, copiar vector[N-i+1] en vector[i] y asignar aux a vector[N-i+1]."
        },
        {
          "@type": "HowToStep",
          "name": "Imprimir el vector invertido resultante",
          "text": "Recorrer el arreglo desde 1 hasta N imprimiendo la secuencia ya reorganizada."
        }
      ]
    },
    {
      "@type": "FAQPage",
      "mainEntity": [
        {
          "@type": "Question",
          "name": "¿Por qué solo se recorre hasta trunc(N/2) para invertir un vector?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Porque si se recorre el arreglo completo hasta N, los elementos se intercambian dos veces y vuelven a quedar en su orden original."
          }
        },
        {
          "@type": "Question",
          "name": "¿Cuál es la complejidad de memoria de la inversión in-situ?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Es O(1) de memoria adicional porque solo emplea una variable auxiliar de tipo entero para realizar las transferencias."
          }
        },
        {
          "@type": "Question",
          "name": "¿Qué ocurre si el tamaño del arreglo es impar?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "El elemento central matemático permanece exactamente en su posición original sin ser modificado, lo cual es matemáticamente correcto."
          }
        }
      ]
    }
  ]
}
</script></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Algoritmo para Contar Números Pares en un Arreglo en PSeInt: Guía y Diagrama</title>
		<link>https://pseint.org/contar-pares-arreglo-pseint/</link>
		
		<dc:creator><![CDATA[El Profe Juan]]></dc:creator>
		<pubDate>Wed, 14 Oct 2026 16:29:17 +0000</pubDate>
				<category><![CDATA[Arreglos y Matrices]]></category>
		<guid isPermaLink="false">https://pseint.org/contar-pares-arreglo-pseint/</guid>

					<description><![CDATA[Aprende a contar números pares en un arreglo en PSeInt con el operador MOD 2. Incluye diagrama de flujo DFD, prueba de escritorio, código y ejercicios.]]></description>
										<content:encoded><![CDATA[<style>
.entry-title, h1.entry-title {
    max-width: 860px !important;
    margin-left: auto !important;
    margin-right: auto !important;
    text-wrap: balance !important;
    line-height: 1.25 !important;
}
</style>
<article style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1e293b; line-height: 1.8; max-width: 100%;">
<p>    <!-- 1. HEADER METADATA BADGES --></p>
<header style="margin-bottom: 35px;">
<div style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px;">
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #e0f2fe; color: #0369a1; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 700; text-transform: uppercase; line-height: 1.2;">Nivel: Básico &#8211; Intermedio</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #f1f5f9; color: #475569; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Estructura: Bucle Para con Condicional Si</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #fef3c7; color: #b45309; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Operador Clave: Aritmética Modular (MOD 2)</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #ecfdf5; color: #047857; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">PSeInt: Compatible Estricto y Flexible</span>
        </div>
<p>        <!-- BLUF BOX (Bottom Line Up Front) --></p>
<div style="background: #f8fafc; border-left: 5px solid #2563eb; padding: 24px; border-radius: 0 10px 10px 0; box-shadow: 0 2px 4px rgba(0,0,0,0.03);">
<p style="margin: 0 0 12px 0; font-size: 1.12rem; color: #1e293b; font-weight: 600;">
                El <strong>algoritmo para contar números pares en un arreglo en PSeInt</strong> implementa el patrón de <strong>conteo condicional</strong>: recorre linealmente el vector evaluando cada casilla con el operador módulo (<code>vector[i] MOD 2 = 0</code>) e incrementa en una unidad un contador entero inicializado en cero (<code>cantPares &lt;- cantPares + 1</code>).
            </p>
<p style="margin: 0; font-size: 0.98rem; color: #475569;">
                <strong>Complejidad y Rendimiento:</strong> Requiere complejidad temporal lineal \(O(N)\) al realizar una única pasada sobre los \(N\) elementos, y complejidad espacial \(O(1)\) adicional de memoria si solo se cuenta, o \(O(N)\) si los elementos pares son filtrados y derivados hacia un nuevo arreglo independiente.
            </p>
</p></div>
</header>
<p>    <!-- SECTION 1: THEORY & MODULO OPERATOR --></p>
<h2>Fundamentos del Conteo Condicional y la Aritmética Modular en Arreglos</h2>
<p>
        El filtrado y conteo de datos bajo un criterio algebraico específico es una de las competencias primordiales de la algoritmia. Para discriminar si un valor entero \(k\) es par o impar en pseudocódigo formal de PSeInt, se recurre a la división entera euclidiana y al cálculo del residuo mediante el operador <code>MOD</code> (o el símbolo de porcentaje <code>%</code>):
    </p>
<div style="background: #f1f5f9; border-left: 4px solid #0284c7; padding: 18px; border-radius: 0 8px 8px 0; margin: 20px 0; font-size: 0.95rem; color: #0f172a;">
        <strong>Definición formal de paridad:</strong> Un número entero \(n\) es par si y solo si existe un entero \(k\) tal que \(n = 2k\). En consecuencia, al dividir \(n\) entre 2, el cociente es exacto y el residuo es estrictamente \(0\):</p>
<div style="margin-top: 8px; font-family: monospace; font-size: 1.05rem; color: #0369a1; font-weight: 700;">
            Si (vector[i] MOD 2 = 0) Entonces  // El elemento es par
        </div>
</p></div>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 18px; margin: 25px 0;">
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #1e40af; font-size: 1.05rem;">1. Inicialización a Cero del Contador</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                El contador (habitualmente nombrado <code>cantPares</code> o <code>totalPares</code>) debe fijarse en <code>0</code> antes de abrir el bucle. Omitir esta inicialización provoca lecturas basura o fallos en perfiles estrictos.
            </p>
</p></div>
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #047857; font-size: 1.05rem;">2. El Caso Especial del Número Cero (0)</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                En matemáticas y programación estándar, <strong>el 0 es considerado un número par</strong> ya que \(0 = 2 \times 0\) y \(0 \text{ MOD } 2 = 0\). Si su ejercicio requiere excluir ceros, debe añadirse la condición <code>Y vector[i] &lt;&gt; 0</code>.
            </p>
</p></div>
</p></div>
<p>    <!-- SECTION 2: EXERCISE 1 (CORE EVEN NUMBERS COUNTER) --></p>
<h2>Ejercicio 1 Algoritmo Básico para Contar y Listar Números Pares en un Vector</h2>
<p>
        En esta implementación fundamental, definimos un vector con 6 números enteros predefinidos. Mediante el <a href="/para-hasta-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">bucle Para</a> y la estructura <a href="/si-entonces-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">condicional Si-Entonces</a>, el algoritmo identifica cada par, imprime su ubicación y computa el total:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Perfil Estricto y Flexible)</span><br />
            <span style="background: #2563eb; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Conteo y Listado Básico</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo ContarParesVector
    // 1. Declaración estricta de variables y dimensiones
    Definir N, i, cantPares Como Entero
    Definir vector Como Entero
    
    N &lt;- 6
    Dimension vector[6]
    
    // 2. Carga de datos de muestra
    vector[1] &lt;- 14
    vector[2] &lt;- 7
    vector[3] &lt;- 22
    vector[4] &lt;- 35
    vector[5] &lt;- 80
    vector[6] &lt;- 91
    
    Escribir "=== CONTEO DE NÚMEROS PARES EN EL ARREGLO ==="
    Escribir "Valores analizados: [14, 7, 22, 35, 80, 91]"
    Escribir "--------------------------------------------"
    
    // 3. Inicialización del acumulador de conteo
    cantPares &lt;- 0
    
    // 4. Recorrido secuencial e inspección de paridad
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        Si vector[i] MOD 2 = 0 Entonces
            cantPares &lt;- cantPares + 1
            Escribir "-> Elemento Par detectado en índice [", i, "]: ", vector[i]
        FinSi
    FinPara
    
    // 5. Presentación del reporte final
    Escribir "--------------------------------------------"
    Escribir "Total de números pares hallados: ", cantPares
    Escribir "Total de números impares (por complemento): ", N - cantPares
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 3: FLOWCHART --></p>
<h2>Diagrama de Flujo del Algoritmo de Conteo de Pares</h2>
<p>
        El siguiente diagrama de flujo estructurado bajo el estándar de PSeInt ilustra cómo se canaliza la bifurcación condicional modular en cada paso de la iteración:
    </p>
<figure style="margin: 30px auto; text-align: center; max-width: 780px;">
<div style="background: #ffffff; padding: 16px; border: 1px solid #e2e8f0; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.06);">
            <img decoding="async" src="https://pseint.org/wp-content/uploads/2026/11/contar-pares-arreglo-pseint-diagrama-flujo.png" 
                 alt="Diagrama de flujo del algoritmo para contar números pares en un arreglo en PSeInt" 
                 style="max-width: 100%; height: auto; border-radius: 8px; display: block; margin: 0 auto;" />
        </div><figcaption style="margin-top: 10px; font-size: 0.88rem; color: #64748b; font-style: italic;">
            Figura 1. Diagrama de flujo oficial DFD en PSeInt detallando el ciclo de recorrido, el rombo de decisión del residuo y el incremento del acumulador.<br />
        </figcaption></figure>
<p>    <!-- SECTION 4: TRACE TABLE --></p>
<h2>Prueba de Escritorio Detallada con Casos Mixtos y Casos Borde</h2>
<p>
        Para comprobar exhaustivamente que la lógica no presenta fallos silenciosos, ejecutamos una prueba de escritorio formal que abarca arreglos balanceados, colecciones homogéneas, negativos y ceros:
    </p>
<div style="overflow-x: auto; margin: 25px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.9rem; text-align: center; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
<thead style="background-color: #1e293b; color: #ffffff;">
<tr>
<th style="padding: 10px 14px;">Escenario / Vector</th>
<th style="padding: 10px 14px;">Tamaño (N)</th>
<th style="padding: 10px 14px;">Evaluación MOD 2 por Elemento</th>
<th style="padding: 10px 14px;">Valores Pares Encontrados</th>
<th style="padding: 10px 14px;">Contador Final</th>
<th style="padding: 10px 14px;">Resultado Teórico</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">1. Vector Mixto Balanceado<br /><code>[4, 7, 12, 19, 8, 21]</code></td>
<td style="padding: 10px 14px;">6</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">0, 1, 0, 1, 0, 1</td>
<td style="padding: 10px 14px; color: #166534; font-weight: 600;">4, 12, 8</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">3</td>
<td style="padding: 10px 14px; color: #166534;">Correcto (3 pares, 3 impares)</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 10px 14px; font-weight: 600;">2. 100% Números Pares<br /><code>[2, 4, 6, 8, 10]</code></td>
<td style="padding: 10px 14px;">5</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">0, 0, 0, 0, 0</td>
<td style="padding: 10px 14px; color: #166534; font-weight: 600;">Todos los 5 elementos</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">5</td>
<td style="padding: 10px 14px; color: #166534;">Correcto (cantPares = N)</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">3. 100% Números Impares<br /><code>[1, 3, 5, 7, 9]</code></td>
<td style="padding: 10px 14px;">5</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">1, 1, 1, 1, 1</td>
<td style="padding: 10px 14px; color: #991b1b; font-weight: 600;">Ninguno</td>
<td style="padding: 10px 14px; font-weight: 700; color: #991b1b;">0</td>
<td style="padding: 10px 14px; color: #166534;">Correcto (cantPares = 0)</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 10px 14px; font-weight: 600;">4. Caso con Cero y Negativos<br /><code>[0, -4, -3, 6, -8]</code></td>
<td style="padding: 10px 14px;">5</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">0, 0, -1 ó 1, 0, 0</td>
<td style="padding: 10px 14px; color: #166534; font-weight: 600;">0, -4, 6, -8</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">4</td>
<td style="padding: 10px 14px; color: #166534;">Correcto (0 y pares negativos)</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">5. Arreglo Unitario Borde<br /><code>[14]</code></td>
<td style="padding: 10px 14px;">1</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">0</td>
<td style="padding: 10px 14px; color: #166534; font-weight: 600;">14</td>
<td style="padding: 10px 14px; font-weight: 700; color: #1e40af;">1</td>
<td style="padding: 10px 14px; color: #166534;">Correcto (1 pase inmediato)</td>
</tr>
</tbody>
</table></div>
<p>    <!-- SECTION 5: EXERCISE 2 (SIMULTANEOUS COUNT AND ACCUMULATED SUM) --></p>
<h2>Ejercicio 2 Conteo Simultáneo de Pares e Impares con Suma Acumulada</h2>
<p>
        En aplicaciones analíticas avanzadas, suele solicitarse no solo la cantidad de elementos, sino la <strong>suma acumulada independiente</strong> y el promedio de cada grupo. El siguiente código combina contadores y acumuladores para ambos subconjuntos en una única pasada \(O(N)\), relacionándose directamente con nuestro algoritmo de <a href="/suma-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">suma de elementos en arreglos</a>:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Doble Acumulador y Contador)</span><br />
            <span style="background: #059669; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Pares e Impares</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo ConteoYSumaParesImpares
    Definir N, i Como Entero
    Definir cPares, cImpares, sumaPares, sumaImpares Como Entero
    Definir datos Como Entero
    
    N &lt;- 6
    Dimension datos[6]
    datos[1] &lt;- 10
    datos[2] &lt;- 15
    datos[3] &lt;- 20
    datos[4] &lt;- 25
    datos[5] &lt;- 30
    datos[6] &lt;- 33
    
    // Inicialización explícita de contadores y acumuladores
    cPares &lt;- 0
    cImpares &lt;- 0
    sumaPares &lt;- 0
    sumaImpares &lt;- 0
    
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        Si datos[i] MOD 2 = 0 Entonces
            cPares &lt;- cPares + 1
            sumaPares &lt;- sumaPares + datos[i]
        SiNo
            cImpares &lt;- cImpares + 1
            sumaImpares &lt;- sumaImpares + datos[i]
        FinSi
    FinPara
    
    Escribir "=== BALANCE GENERAL DE PARIDAD ==="
    Escribir "Subconjunto Pares:   ", cPares, " elementos | Sumatoria = ", sumaPares
    Escribir "Subconjunto Impares: ", cImpares, " elementos | Sumatoria = ", sumaImpares
    
    Si cPares &gt; 0 Entonces
        Escribir "Promedio de los valores pares: ", sumaPares / cPares
    FinSi
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 6: EXERCISE 3 (FILTERING INTO SEPARATE ARRAYS) --></p>
<h2>Ejercicio 3 Filtrado y Separación de Pares e Impares en Nuevos Arreglos</h2>
<p>
        Un requerimiento común en exámenes universitarios consiste en segregar los elementos pares en un nuevo vector y los impares en otro. Esto introduce la gestión de <strong>índices independientes</strong> para cada arreglo secundario, previniendo celdas vacías o desbordamientos:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Partición en Vectores Derivados)</span><br />
            <span style="background: #9333ea; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Separación Dinámica</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo SepararParesImpares
    Definir N, i, idxP, idxI Como Entero
    Definir origen, pares, impares Como Entero
    
    N &lt;- 6
    Dimension origen[6], pares[6], impares[6]
    
    origen[1] &lt;- 12
    origen[2] &lt;- 5
    origen[3] &lt;- 8
    origen[4] &lt;- 17
    origen[5] &lt;- 20
    origen[6] &lt;- 31
    
    // Contadores que actúan como punteros de escritura
    idxP &lt;- 0
    idxI &lt;- 0
    
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        Si origen[i] MOD 2 = 0 Entonces
            idxP &lt;- idxP + 1
            pares[idxP] &lt;- origen[i]
        SiNo
            idxI &lt;- idxI + 1
            impares[idxI] &lt;- origen[i]
        FinSi
    FinPara
    
    Escribir "=== ARREGLO FILTRADO DE PARES (Total: ", idxP, ") ==="
    Para i &lt;- 1 Hasta idxP Con Paso 1 Hacer
        Escribir Sin Saltar pares[i], " "
    FinPara
    Escribir ""
    
    Escribir "=== ARREGLO FILTRADO DE IMPARES (Total: ", idxI, ") ==="
    Para i &lt;- 1 Hasta idxI Con Paso 1 Hacer
        Escribir Sin Saltar impares[i], " "
    FinPara
    Escribir ""
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 7: EXERCISE 4 (MODULARIZATION WITH FUNCTION) --></p>
<h2>Ejercicio 4 Modularización con Funciones para el Análisis de Paridad</h2>
<p>
        Para cumplir con los principios de modularidad y código limpio, implementamos una <a href="/subproceso-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Función en PSeInt</a> que recibe el arreglo por referencia junto con su tamaño y devuelve el número total de elementos pares:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Función Reutilizable)</span><br />
            <span style="background: #0891b2; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Modular</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">// Subproceso que computa la cantidad de números pares en un vector
Funcion total &lt;- ContarParesEnArreglo(arr Por Referencia, longitud)
    Definir total, k Como Entero
    total &lt;- 0
    Para k &lt;- 1 Hasta longitud Con Paso 1 Hacer
        Si arr[k] MOD 2 = 0 Entonces
            total &lt;- total + 1
        FinSi
    FinPara
FinFuncion

Algoritmo PrincipalConteoModular
    Definir tam, resultadoPares Como Entero
    Definir miLista Como Entero
    
    tam &lt;- 5
    Dimension miLista[5]
    miLista[1] &lt;- 44
    miLista[2] &lt;- 13
    miLista[3] &lt;- 28
    miLista[4] &lt;- 90
    miLista[5] &lt;- 71
    
    // Invocación de la función externa
    resultadoPares &lt;- ContarParesEnArreglo(miLista, tam)
    
    Escribir "=== RESULTADO DE LA FUNCIÓN MODULAR ==="
    Escribir "Cantidad de pares reportados por la función: ", resultadoPares
    Escribir "Porcentaje de paridad en el conjunto: ", (resultadoPares / tam) * 100, "%"
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 8: COMMON MISTAKES --></p>
<h2>Errores Comunes al Trabajar con Pares y Módulos en PSeInt</h2>
<p>
        Al operar con aritmética modular en estructuras de datos repetitivas, los estudiantes suelen encontrarse con dificultades técnicas frecuentes:
    </p>
<div style="display: flex; flex-direction: column; gap: 16px; margin: 25px 0;">
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">1. Confundir el operador de división normal (/) con el operador módulo (MOD)</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Escribir <code>vector[i] / 2 = 0</code> evalúa si la mitad del número es cero, lo cual solo es cierto para el número cero. El operador correcto para verificar divisibilidad es siempre <code>MOD</code> o <code>%</code>.
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">2. Olvidar inicializar el contador en cero</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Si se omite <code>cantPares &lt;- 0</code>, la variable carecerá de un estado previo definido, arrojando excepciones en el perfil estricto de PSeInt o sumando sobre valores impredecibles.
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">3. Desbordar el vector de filtrado (Error 303)</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Al crear arreglos derivados (como en el Ejercicio 3), dimensionar el nuevo vector con un tamaño menor al total original puede causar el <a href="/error-303-pseint/" style="color: #9f1239; text-decoration: underline; font-weight: 700;">Error 303: Subíndice fuera de rango</a> si todos los elementos resultan ser pares.
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">4. Truncamiento al calcular promedios</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Al calcular el promedio de los números pares dividiendo <code>sumaPares / cPares</code>, asegúrese de que el divisor no sea 0 para evitar divisiones indeterminadas. Para revisar más advertencias consulte la <a href="/errores-comunes-pseint/" style="color: #9f1239; text-decoration: underline; font-weight: 700;">guía de errores frecuentes en PSeInt</a>.
            </p>
</p></div>
</p></div>
<p>    <!-- SECTION 9: FAQ --></p>
<h2>Preguntas Frecuentes sobre Vectores y Números Pares en PSeInt</h2>
<div style="display: flex; flex-direction: column; gap: 14px; margin: 25px 0;">
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿El operador % funciona igual que MOD en PSeInt?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                Sí, en PSeInt tanto la palabra clave <code>MOD</code> como el símbolo <code>%</code> son sinónimos equivalentes para calcular el resto de una división entera.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Cómo se determina si un número negativo es par en PSeInt?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                Cualquier número par negativo (por ejemplo, -4 o -8) dividido entre 2 da residuo exacto 0, por lo que <code>(-4) MOD 2 = 0</code> se evalúa como Verdadero automáticamente.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Cómo se relaciona este conteo con la búsqueda de valores en arreglos?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                Mientras que el algoritmo de <a href="/buscar-en-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">búsqueda lineal en un arreglo</a> suele detenerse al hallar la primera coincidencia, el conteo de pares requiere un recorrido exhaustivo de principio a fin sin cortes tempranos.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Se puede ordenar el arreglo antes de contar los pares?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                No es necesario ni recomendable ordenar el vector previamente; ordenar cuesta \(O(N \log N)\) o \(O(N^2)\), mientras que el conteo directo toma solo \(O(N)\).
            </p>
</p></div>
</p></div>
<p>    <!-- CTA & INTERNAL NAVIGATION --></p>
<div style="background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); color: #ffffff; padding: 32px 24px; border-radius: 12px; margin: 40px 0; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.12);">
<h3 style="color: #ffffff; margin-top: 0; font-size: 1.35rem; margin-bottom: 12px;">Continúa Fortaleciendo tus Habilidades en Algoritmia</h3>
<p style="color: #94a3b8; font-size: 1rem; max-width: 680px; margin: 0 auto 24px auto; line-height: 1.6;">
            Explora más algoritmos resueltos paso a paso con diagramas de flujo interactivos, pruebas de escritorio y explicaciones detalladas para todos los niveles formativos.
        </p>
<div><a href="/ejercicios-resueltos/" style="display: inline-flex; align-items: center; justify-content: center; line-height: 1.2; background-color: #2563eb; color: #ffffff; padding: 12px 28px; border-radius: 8px; text-decoration: none; font-weight: 700; font-size: 1rem; transition: background 0.2s ease-in-out;">Explorar Catálogo de Ejercicios Resueltos</a></div>
</p></div>
</article>
<p><!-- JSON-LD SCHEMA METADATA --><br />
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "TechArticle",
      "headline": "Algoritmo para Contar Números Pares en un Arreglo en PSeInt: Guía y Diagrama",
      "description": "Aprende a contar números pares en un arreglo o vector en PSeInt mediante el operador MOD 2, bucles Para, separación de arreglos y modularización con funciones.",
      "proficiencyLevel": "Beginner",
      "inLanguage": "es",
      "author": {
        "@type": "Organization",
        "name": "PSeInt.org"
      }
    },
    {
      "@type": "HowTo",
      "name": "Cómo contar números pares en un vector en PSeInt",
      "description": "Procedimiento paso a paso para recorrer un vector e incrementar un contador cuando los elementos cumplen la condición de paridad.",
      "step": [
        {
          "@type": "HowToStep",
          "name": "Declarar variables y dimensionar el arreglo",
          "text": "Definir las variables de control, el vector y la variable contadora de tipo Entero."
        },
        {
          "@type": "HowToStep",
          "name": "Inicializar el contador en cero",
          "text": "Asignar 0 al contador antes de comenzar el bucle de recorrido."
        },
        {
          "@type": "HowToStep",
          "name": "Recorrer el vector con bucle Para",
          "text": "Iterar desde 1 hasta el tamaño total N evaluando cada posición."
        },
        {
          "@type": "HowToStep",
          "name": "Evaluar la condición modular y acumular",
          "text": "Verificar si vector[i] MOD 2 = 0; de cumplirse, sumar 1 al contador e imprimir el resultado final."
        }
      ]
    },
    {
      "@type": "FAQPage",
      "mainEntity": [
        {
          "@type": "Question",
          "name": "¿El número cero (0) se considera par en PSeInt?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Sí, matemáticamente 0 es par porque 0 MOD 2 arroja 0 de residuo exacto."
          }
        },
        {
          "@type": "Question",
          "name": "¿Cuál es la diferencia entre MOD y la división tradicional?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "MOD devuelve el residuo entero de la división, mientras que la barra (/) calcula el cociente continuo."
          }
        },
        {
          "@type": "Question",
          "name": "¿Cuál es la complejidad algorítmica de contar pares en un vector?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Es de orden O(N) lineal, ya que realiza exactamente una evaluación condicional por cada celda del arreglo."
          }
        }
      ]
    }
  ]
}
</script></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Algoritmo para Buscar un Valor en un Arreglo en PSeInt: Guía y Diagrama</title>
		<link>https://pseint.org/buscar-en-arreglo-pseint/</link>
		
		<dc:creator><![CDATA[El Profe Juan]]></dc:creator>
		<pubDate>Wed, 14 Oct 2026 16:28:22 +0000</pubDate>
				<category><![CDATA[Arreglos y Matrices]]></category>
		<guid isPermaLink="false">https://pseint.org/buscar-en-arreglo-pseint/</guid>

					<description><![CDATA[Guía completa de búsqueda lineal en arreglos con PSeInt usando banderas lógicas. Diagrama de flujo DFD, prueba de escritorio, salida temprana y funciones.]]></description>
										<content:encoded><![CDATA[<style>
.entry-title, h1.entry-title {
    max-width: 860px !important;
    margin-left: auto !important;
    margin-right: auto !important;
    text-wrap: balance !important;
    line-height: 1.25 !important;
}
</style>
<article style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1e293b; line-height: 1.8; max-width: 100%;">
<p>    <!-- 1. HEADER METADATA BADGES --></p>
<header style="margin-bottom: 35px;">
<div style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px;">
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #e0f2fe; color: #0369a1; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 700; text-transform: uppercase; line-height: 1.2;">Nivel: Básico &#8211; Intermedio</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #f1f5f9; color: #475569; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Estructura: Búsqueda Secuencial (Lineal)</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #fef3c7; color: #b45309; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Patrón: Bandera Lógica (Flag Booleano)</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #ecfdf5; color: #047857; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">PSeInt: Compatible Estricto y Flexible</span>
        </div>
<p>        <!-- BLUF BOX (Bottom Line Up Front) --></p>
<div style="background: #f8fafc; border-left: 5px solid #2563eb; padding: 24px; border-radius: 0 10px 10px 0; box-shadow: 0 2px 4px rgba(0,0,0,0.03);">
<p style="margin: 0 0 12px 0; font-size: 1.12rem; color: #1e293b; font-weight: 600;">
                El <strong>algoritmo para buscar un valor en un arreglo en PSeInt</strong> implementa una <strong>búsqueda secuencial (lineal)</strong> recorriendo cada celda del vector desde el índice inicial hasta hallar el dato solicitado, empleando una variable booleana como <strong>bandera de control</strong> (<code>encontrado &lt;- Falso</code>) y un centinela para registrar la posición (<code>posicion &lt;- -1</code>).
            </p>
<p style="margin: 0; font-size: 0.98rem; color: #475569;">
                <strong>Complejidad algorítmica:</strong> Presenta un caso mejor de \(O(1)\) cuando el dato se encuentra en el primer índice analizado, y un caso peor / promedio de \(O(N)\) si el elemento reside en el último casillero o no existe en la colección, requiriendo \(N\) comparaciones exhaustivas.
            </p>
</p></div>
</header>
<p>    <!-- SECTION 1: THEORY & FLAG PATTERN --></p>
<h2>Fundamentos de la Búsqueda Secuencial y el Patrón de la Bandera Lógica</h2>
<p>
        En la programación estructurada y el diseño algorítmico, localizar un elemento dentro de una colección no ordenada es uno de los problemas clásicos más recurrentes. A diferencia de las estructuras ordenadas que permiten algoritmos logarítmicos como la búsqueda binaria, los arreglos unidimensionales genéricos requieren un examen progresivo celda por celda.
    </p>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 18px; margin: 25px 0;">
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #1e40af; font-size: 1.05rem;">1. Variable Centinela o Bandera (Flag)</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                Se define de tipo <code>Logico</code> e inicia en <code>Falso</code>. Al encontrar una coincidencia, conmuta su estado a <code>Verdadero</code>. Evita imprimir mensajes repetitivos dentro del bucle.
            </p>
</p></div>
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #047857; font-size: 1.05rem;">2. Puntero de Posición (-1)</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                Se inicializa en un valor inválido (como <code>-1</code> o <code>0</code>). Si la búsqueda tiene éxito, almacena el índice donde ocurrió el acierto; si fracasa, permanece inalterado para confirmación posterior.
            </p>
</p></div>
</p></div>
<p>    <!-- COMPARISON TABLE: LINEAR VS BINARY --></p>
<div style="overflow-x: auto; margin: 25px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.95rem; text-align: left; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
<thead style="background-color: #1e293b; color: #ffffff;">
<tr>
<th style="padding: 12px 16px;">Criterio Técnico</th>
<th style="padding: 12px 16px;">Búsqueda Lineal / Secuencial</th>
<th style="padding: 12px 16px;">Búsqueda Binaria (Dicotómica)</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 16px; font-weight: 600;">Requisito previo del arreglo</td>
<td style="padding: 12px 16px; color: #166534; font-weight: 600;">Ninguno (funciona en arreglos desordenados)</td>
<td style="padding: 12px 16px; color: #991b1b;">Obligatorio: Arreglo previamente ordenado</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 12px 16px; font-weight: 600;">Complejidad en el Mejor Caso</td>
<td style="padding: 12px 16px;">\(O(1)\) (primer elemento coincide)</td>
<td style="padding: 12px 16px;">\(O(1)\) (elemento central coincide)</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 16px; font-weight: 600;">Complejidad en el Peor Caso</td>
<td style="padding: 12px 16px; color: #b45309; font-weight: 600;">\(O(N)\) (recorre todas las \(N\) casillas)</td>
<td style="padding: 12px 16px; color: #166534; font-weight: 600;">\(O(\log_2 N)\) (divide el espacio a la mitad)</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 12px 16px; font-weight: 600;">Complejidad de Implementación</td>
<td style="padding: 12px 16px;">Extremadamente simple (1 bucle e 1 condicional)</td>
<td style="padding: 12px 16px;">Moderada (manejo de punteros izquierda/derecha/medio)</td>
</tr>
</tbody>
</table></div>
<p>    <!-- SECTION 2: EXERCISE 1 (CORE SEARCH WITH FOR AND BOOLEAN FLAG) --></p>
<h2>Ejercicio 1 Algoritmo Clásico de Búsqueda Lineal con Bandera Booleana</h2>
<p>
        El siguiente algoritmo solicita al usuario un valor numérico y recorre un arreglo de 6 elementos mediante el <a href="/para-hasta-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">ciclo Para</a>. Al finalizar la iteración, evalúa el estado de la bandera booleana para mostrar un único mensaje claro:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Perfil Estricto y Flexible)</span><br />
            <span style="background: #2563eb; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Búsqueda Clásica</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo BuscarArregloBandera
    // 1. Declaración estricta de variables y dimensiones
    Definir N, i, valorBuscado, posicion Como Entero
    Definir encontrado Como Logico
    Definir vector Como Entero
    
    N &lt;- 6
    Dimension vector[6]
    
    // 2. Asignación de datos en el vector
    vector[1] &lt;- 14
    vector[2] &lt;- 45
    vector[3] &lt;- 88
    vector[4] &lt;- 23
    vector[5] &lt;- 50
    vector[6] &lt;- 23
    
    Escribir "=== BÚSQUEDA SECUENCIAL EN ARREGLO ==="
    Escribir Sin Saltar "Ingrese el número entero que desea buscar: "
    Leer valorBuscado
    
    // 3. Inicialización del patrón de bandera
    encontrado &lt;- Falso
    posicion &lt;- -1
    
    // 4. Recorrido secuencial exhaustivo
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        Si vector[i] = valorBuscado Entonces
            // Registrar solo la primera ocurrencia encontrada
            Si NO encontrado Entonces
                encontrado &lt;- Verdadero
                posicion &lt;- i
            FinSi
        FinSi
    FinPara
    
    // 5. Emisión de resultado final fuera del ciclo
    Escribir "--------------------------------------------"
    Si encontrado Entonces
        Escribir "¡Valor localizado! El número ", valorBuscado, " se encuentra en la posición: ", posicion
    SiNo
        Escribir "El número ", valorBuscado, " no existe en el arreglo examinado."
    FinSi
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 3: FLOWCHART --></p>
<h2>Diagrama de Flujo del Algoritmo de Búsqueda Secuencial</h2>
<p>
        El diagrama de flujo formal estandarizado bajo la notación DFD de PSeInt refleja cómo la condición de evaluación interna actualiza el estado de la bandera sin interrumpir el flujo estructurado:
    </p>
<figure style="margin: 30px auto; text-align: center; max-width: 780px;">
<div style="background: #ffffff; padding: 16px; border: 1px solid #e2e8f0; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.06);">
            <img decoding="async" src="https://pseint.org/wp-content/uploads/2026/11/buscar-en-arreglo-pseint-diagrama-flujo.png" 
                 alt="Diagrama de flujo del algoritmo de búsqueda lineal en un arreglo con bandera lógica en PSeInt" 
                 style="max-width: 100%; height: auto; border-radius: 8px; display: block; margin: 0 auto;" />
        </div><figcaption style="margin-top: 10px; font-size: 0.88rem; color: #64748b; font-style: italic;">
            Figura 1. Diagrama de flujo oficial DFD en PSeInt mostrando el flujo secuencial, la bifurcación lógica condicional y la actualización de la bandera booleana.<br />
        </figcaption></figure>
<p>    <!-- SECTION 4: TRACE TABLE --></p>
<h2>Prueba de Escritorio Detallada con Casos de Búsqueda Críticos</h2>
<p>
        La verificación manual mediante una prueba de escritorio (trace table) garantiza la robustez del algoritmo ante diferentes escenarios de búsqueda sobre el vector base <code>[14, 45, 88, 23, 50, 23]</code> con \(N = 6\):
    </p>
<div style="overflow-x: auto; margin: 25px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.9rem; text-align: center; background: #ffffff; border-radius: 8px; overflow: hidden; box-shadow: 0 2px 5px rgba(0,0,0,0.05);">
<thead style="background-color: #1e293b; color: #ffffff;">
<tr>
<th style="padding: 10px 14px;">Caso</th>
<th style="padding: 10px 14px;">Clave</th>
<th style="padding: 10px 14px;">Iteración (i)</th>
<th style="padding: 10px 14px;">vector[i]</th>
<th style="padding: 10px 14px;">¿vector[i] = Clave?</th>
<th style="padding: 10px 14px;">Estado Bandera</th>
<th style="padding: 10px 14px;">Posición Final</th>
<th style="padding: 10px 14px;">Salida en Consola</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">1. Mejor Caso</td>
<td style="padding: 10px 14px;">14</td>
<td style="padding: 10px 14px;">i = 1</td>
<td style="padding: 10px 14px;">14</td>
<td style="padding: 10px 14px; color: #166534; font-weight: 600;">Verdadero</td>
<td style="padding: 10px 14px; color: #166534;">Verdadero</td>
<td style="padding: 10px 14px; font-weight: 700;">1</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">Localizado en posición: 1</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 10px 14px; font-weight: 600;">2. Caso Intermedio</td>
<td style="padding: 10px 14px;">88</td>
<td style="padding: 10px 14px;">i = 1 .. 3</td>
<td style="padding: 10px 14px;">88</td>
<td style="padding: 10px 14px; color: #166534; font-weight: 600;">Verdadero (en i=3)</td>
<td style="padding: 10px 14px; color: #166534;">Verdadero</td>
<td style="padding: 10px 14px; font-weight: 700;">3</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">Localizado en posición: 3</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">3. Elemento Final</td>
<td style="padding: 10px 14px;">50</td>
<td style="padding: 10px 14px;">i = 1 .. 5</td>
<td style="padding: 10px 14px;">50</td>
<td style="padding: 10px 14px; color: #166534; font-weight: 600;">Verdadero (en i=5)</td>
<td style="padding: 10px 14px; color: #166534;">Verdadero</td>
<td style="padding: 10px 14px; font-weight: 700;">5</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">Localizado en posición: 5</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background-color: #f8fafc;">
<td style="padding: 10px 14px; font-weight: 600;">4. Clave Ausente</td>
<td style="padding: 10px 14px;">99</td>
<td style="padding: 10px 14px;">i = 1 .. 6</td>
<td style="padding: 10px 14px;">Todos distintos</td>
<td style="padding: 10px 14px; color: #991b1b; font-weight: 600;">Falso siempre</td>
<td style="padding: 10px 14px; color: #991b1b;">Falso</td>
<td style="padding: 10px 14px; font-weight: 700;">-1</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">No existe en el arreglo</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 10px 14px; font-weight: 600;">5. Duplicados</td>
<td style="padding: 10px 14px;">23</td>
<td style="padding: 10px 14px;">i = 1 .. 6</td>
<td style="padding: 10px 14px;">23 (en i=4 e i=6)</td>
<td style="padding: 10px 14px; color: #166534; font-weight: 600;">Verdadero (i=4 e i=6)</td>
<td style="padding: 10px 14px; color: #166534;">Verdadero</td>
<td style="padding: 10px 14px; font-weight: 700;">4 (1ª aparición)</td>
<td style="padding: 10px 14px; font-family: monospace; font-size: 0.82rem;">Localizado en posición: 4</td>
</tr>
</tbody>
</table></div>
<p>    <!-- SECTION 5: EXERCISE 2 (EARLY EXIT WITH WHILE) --></p>
<h2>Ejercicio 2 Búsqueda Eficiente con Salida Temprana Mediante Bucle Mientras</h2>
<p>
        En el ejercicio clásico con ciclo <code>Para</code>, la computadora continúa recorriendo las celdas restantes incluso después de haber hallado el elemento. Para optimizar el rendimiento y detener el ciclo de inmediato cuando se detecta la coincidencia, se utiliza una condición compuesta con el <a href="/mientras-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">bucle Mientras</a>:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Perfil Estricto y Flexible)</span><br />
            <span style="background: #059669; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Optimización Salida Temprana</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo BuscarArregloMientras
    Definir N, i, clave, posHallada Como Entero
    Definir hallado Como Logico
    Definir lista Como Entero
    
    N &lt;- 5
    Dimension lista[5]
    lista[1] &lt;- 12
    lista[2] &lt;- 34
    lista[3] &lt;- 56
    lista[4] &lt;- 78
    lista[5] &lt;- 90
    
    Escribir "=== BÚSQUEDA OPTIMIZADA (CORTE INMEDIATO) ==="
    Escribir Sin Saltar "Ingrese el valor a localizar: "
    Leer clave
    
    hallado &lt;- Falso
    posHallada &lt;- -1
    i &lt;- 1
    
    // Condición combinada: se repite sólo mientras haya casillas Y no se haya encontrado el dato
    Mientras (i &lt;= N) Y (NO hallado) Hacer
        Si lista[i] = clave Entonces
            hallado &lt;- Verdadero
            posHallada &lt;- i
        SiNo
            i &lt;- i + 1
        FinSi
    FinMientras
    
    Escribir "--------------------------------------------"
    Si hallado Entonces
        Escribir "¡Elemento localizado en el índice [", posHallada, "]!"
        Escribir "Total de comparaciones ejecutadas: ", i
    SiNo
        Escribir "Elemento no encontrado tras revisar las ", N, " posiciones del arreglo."
    FinSi
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 6: EXERCISE 3 (MULTIPLE OCCURRENCES) --></p>
<h2>Ejercicio 3 Búsqueda con Ocurrencias Múltiples y Conteo de Coincidencias</h2>
<p>
        Cuando los arreglos admiten valores repetidos (por ejemplo, notas de alumnos o inventarios de almacén), el objetivo suele cambiar: no basta con saber si existe, sino cuántas veces aparece y en cuáles posiciones específicas se ubica:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Perfil Estricto y Flexible)</span><br />
            <span style="background: #9333ea; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Ocurrencias Múltiples</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo BuscarOcurrenciasMultiples
    Definir N, i, buscado, totalCoincidencias Como Entero
    Definir datos Como Entero
    
    N &lt;- 8
    Dimension datos[8]
    datos[1] &lt;- 10
    datos[2] &lt;- 25
    datos[3] &lt;- 30
    datos[4] &lt;- 25
    datos[5] &lt;- 70
    datos[6] &lt;- 25
    datos[7] &lt;- 90
    datos[8] &lt;- 10
    
    Escribir "=== BÚSQUEDA DE TODAS LAS COINCIDENCIAS ==="
    Escribir Sin Saltar "Ingrese el número a buscar: "
    Leer buscado
    
    totalCoincidencias &lt;- 0
    Escribir "Inspeccionando posiciones del arreglo..."
    
    Para i &lt;- 1 Hasta N Con Paso 1 Hacer
        Si datos[i] = buscado Entonces
            totalCoincidencias &lt;- totalCoincidencias + 1
            Escribir "  -> Coincidencia ", totalCoincidencias, " detectada en la posición: [", i, "]"
        FinSi
    FinPara
    
    Escribir "--------------------------------------------"
    Si totalCoincidencias &gt; 0 Entonces
        Escribir "Conclusión: El número ", buscado, " se repite un total de ", totalCoincidencias, " veces."
    SiNo
        Escribir "Conclusión: El número ", buscado, " no presenta ninguna ocurrencia en el arreglo."
    FinSi
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 7: EXERCISE 4 (MODULARIZATION WITH FUNCTION) --></p>
<h2>Ejercicio 4 Modularización con Funciones y Retorno del Índice de Búsqueda</h2>
<p>
        Siguiendo las mejores prácticas de ingeniería de software, la lógica de búsqueda debe desacoplarse de la interfaz de entrada y salida mediante una <a href="/subproceso-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Función o Subproceso en PSeInt</a>. Esta función recibe el vector, su tamaño y la clave, retornando el índice hallado o el valor centinela <code>-1</code>:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Modular con Retorno)</span><br />
            <span style="background: #0891b2; color: #ffffff; font-size: 0.75rem; padding: 2px 8px; border-radius: 4px; font-weight: 600;">Función Reutilizable</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">// Subproceso modular que busca un elemento y devuelve su índice (-1 si no existe)
Funcion posRetorno &lt;- BuscarEnVector(arr Por Referencia, tam, objetivo)
    Definir posRetorno, k Como Entero
    Definir encontrado Como Logico
    
    posRetorno &lt;- -1
    encontrado &lt;- Falso
    k &lt;- 1
    
    Mientras (k &lt;= tam) Y (NO encontrado) Hacer
        Si arr[k] = objetivo Entonces
            posRetorno &lt;- k
            encontrado &lt;- Verdadero
        SiNo
            k &lt;- k + 1
        FinSi
    FinMientras
FinFuncion

Algoritmo PrincipalModular
    Definir cant, busqueda, resultado Como Entero
    Definir numeros Como Entero
    
    cant &lt;- 5
    Dimension numeros[5]
    numeros[1] &lt;- 15
    numeros[2] &lt;- 42
    numeros[3] &lt;- 8
    numeros[4] &lt;- 99
    numeros[5] &lt;- 63
    
    Escribir "=== BÚSQUEDA MODULAR MEDIANTE FUNCIÓN ==="
    Escribir Sin Saltar "Ingrese el número a verificar: "
    Leer busqueda
    
    // Invocación de la función externa
    resultado &lt;- BuscarEnVector(numeros, cant, busqueda)
    
    Escribir "--------------------------------------------"
    Si resultado &lt;&gt; -1 Entonces
        Escribir "Resultado: El valor fue encontrado con éxito en el índice ", resultado, "."
    SiNo
        Escribir "Resultado: El código devuelto es -1 (El valor no existe en la colección)."
    FinSi
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 8: COMMON MISTAKES --></p>
<h2>Errores Comunes al Buscar en Arreglos de PSeInt</h2>
<p>
        Durante el desarrollo de algoritmos de búsqueda lineal en PSeInt, los programadores cometen habitualmente cuatro errores conceptuales y sintácticos frecuentes:
    </p>
<div style="display: flex; flex-direction: column; gap: 16px; margin: 25px 0;">
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">1. Imprimir «No encontrado» dentro del cuerpo del bucle</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Colocar un bloque <code>SiNo Escribir "No encontrado"</code> dentro del ciclo <code>Para</code> genera un mensaje de error por cada elemento que no coincida. Si el arreglo tiene 100 posiciones y el dato está al final, el programa imprimirá 99 veces «No encontrado» antes del mensaje de éxito. <strong>Solución:</strong> Utilizar siempre la bandera lógica y evaluar el resultado únicamente al finalizar el bucle.
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">2. Desbordamiento del índice y el temido Error 303</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                En los bucles <code>Mientras</code>, incrementar el contador antes de evaluar o intentar acceder a una posición fuera de los límites de la dimensión provoca el clásico <a href="/error-303-pseint/" style="color: #9f1239; text-decoration: underline; font-weight: 700;">Error 303: Subíndice fuera de rango</a>. Asegúrese de que el contador no supere la cota superior del arreglo.
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">3. Olvidar inicializar la bandera lógica</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                En perfiles estrictos de PSeInt, intentar leer o evaluar una variable que no ha recibido un valor previo dispara una excepción por variable no inicializada. Establezca siempre <code>encontrado &lt;- Falso</code> antes de iniciar cualquier iteración.
            </p>
</p></div>
<div style="background: #fff1f2; border-left: 4px solid #e11d48; padding: 16px 20px; border-radius: 0 8px 8px 0;">
<h3 style="margin: 0 0 8px 0; color: #9f1239; font-size: 1rem;">4. Sobrescritura de la posición en elementos repetidos</h3>
<p style="margin: 0; font-size: 0.92rem; color: #4c0519;">
                Si el valor buscado aparece varias veces y el código asigna <code>posicion &lt;- i</code> sin condicionar mediante <code>Si NO encontrado</code>, la variable conservará el índice de la <em>última</em> aparición en lugar de la <em>primera</em>. Para revisar más problemas típicos consulte la <a href="/errores-comunes-pseint/" style="color: #9f1239; text-decoration: underline; font-weight: 700;">guía completa de errores en PSeInt</a>.
            </p>
</p></div>
</p></div>
<p>    <!-- SECTION 9: FAQ --></p>
<h2>Preguntas Frecuentes sobre Búsqueda en Vectores con PSeInt</h2>
<div style="display: flex; flex-direction: column; gap: 14px; margin: 25px 0;">
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Por qué se inicializa la posición encontrada en -1 y no en 0?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                En PSeInt, la numeración de los arreglos puede comenzar en 1 (por defecto en perfil flexible y estricto) o en 0 (si se activa en la configuración del lenguaje). El valor <code>-1</code> es universalmente reconocido como un índice inválido en todas las configuraciones, garantizando que jamás coincida con una posición legítima.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Se puede detener un ciclo Para antes de que llegue a su límite en PSeInt?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                PSeInt no admite la instrucción <code>break</code> habitual de lenguajes como C o Python dentro de un ciclo <code>Para</code>. Por esa razón, cuando se requiere una salida temprana obligatoria, la estructura idónea recomendada es el bucle <code>Mientras</code> combinando la condición con la bandera lógica.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Cuál es la diferencia entre buscar el mayor elemento y buscar un valor específico?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                Al calcular el valor máximo o mínimo (como en nuestro <a href="/mayor-menor-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">algoritmo de mayor y menor en arreglos</a>), es obligatorio recorrer el 100% del vector porque cualquier elemento posterior podría superar al actual. En la búsqueda puntual, el algoritmo puede detenerse en cuanto encuentra la coincidencia.
            </p>
</p></div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 18px;">
<h3 style="margin: 0 0 8px 0; font-size: 1rem; color: #1e293b;">¿Cómo se vincula este ejercicio con otras operaciones sobre vectores?</h3>
<p style="margin: 0; font-size: 0.92rem; color: #475569;">
                La búsqueda secuencial comparte la técnica de recorrido lineal utilizada en la <a href="/suma-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">suma de elementos de un arreglo</a> y en el <a href="/promedio-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">cálculo del promedio de un vector</a>, consolidando el dominio integral de las estructuras de datos indexadas.
            </p>
</p></div>
</p></div>
<p>    <!-- CTA & INTERNAL NAVIGATION --></p>
<div style="background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); color: #ffffff; padding: 32px 24px; border-radius: 12px; margin: 40px 0; text-align: center; box-shadow: 0 4px 15px rgba(0,0,0,0.12);">
<h3 style="color: #ffffff; margin-top: 0; font-size: 1.35rem; margin-bottom: 12px;">Continúa Fortaleciendo tus Habilidades en Algoritmia</h3>
<p style="color: #94a3b8; font-size: 1rem; max-width: 680px; margin: 0 auto 24px auto; line-height: 1.6;">
            Explora más algoritmos resueltos paso a paso con diagramas de flujo interactivos, pruebas de escritorio y explicaciones detalladas para todos los niveles formativos.
        </p>
<div><a href="/ejercicios-resueltos/" style="display: inline-flex; align-items: center; justify-content: center; line-height: 1.2; background-color: #2563eb; color: #ffffff; padding: 12px 28px; border-radius: 8px; text-decoration: none; font-weight: 700; font-size: 1rem; transition: background 0.2s ease-in-out;">Explorar Catálogo de Ejercicios Resueltos</a></div>
</p></div>
</article>
<p><!-- JSON-LD SCHEMA METADATA --><br />
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "TechArticle",
      "headline": "Algoritmo para Buscar un Valor en un Arreglo en PSeInt: Guía y Diagrama",
      "description": "Aprende a buscar un elemento en un arreglo o vector en PSeInt mediante búsqueda lineal secuencial, banderas lógicas (flags), salida temprana y modularización con funciones.",
      "proficiencyLevel": "Beginner",
      "inLanguage": "es",
      "author": {
        "@type": "Organization",
        "name": "PSeInt.org"
      }
    },
    {
      "@type": "HowTo",
      "name": "Cómo buscar un valor en un vector en PSeInt con bandera lógica",
      "description": "Pasos estructurados para diseñar e implementar la búsqueda secuencial de un elemento en un arreglo unidimensional usando PSeInt.",
      "step": [
        {
          "@type": "HowToStep",
          "name": "Declarar y dimensionar el vector",
          "text": "Definir las variables numéricas, la bandera booleana e inicializar el arreglo con la instrucción Dimension."
        },
        {
          "@type": "HowToStep",
          "name": "Inicializar el flag lógico y el índice centinela",
          "text": "Asignar Falso a la variable encontrado y -1 a la variable de posición previa al ciclo de búsqueda."
        },
        {
          "@type": "HowToStep",
          "name": "Recorrer las celdas comparando con la clave buscada",
          "text": "Utilizar un bucle Para o Mientras para evaluar si vector[i] es igual al valor solicitado por el usuario."
        },
        {
          "@type": "HowToStep",
          "name": "Actualizar el estado y evaluar fuera del bucle",
          "text": "Si coincide, conmutar la bandera a Verdadero y almacenar la posición. Al finalizar el ciclo, informar el resultado mediante condicional Si."
        }
      ]
    },
    {
      "@type": "FAQPage",
      "mainEntity": [
        {
          "@type": "Question",
          "name": "¿Por qué se inicializa la posición encontrada en -1 y no en 0?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "El valor -1 es un índice universalmente inválido en cualquier configuración de PSeInt (tanto con base 0 como con base 1), evitando colisiones con celdas legítimas."
          }
        },
        {
          "@type": "Question",
          "name": "¿Se puede detener un ciclo Para antes de que llegue a su límite en PSeInt?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "PSeInt no dispone de la instrucción break en bucles Para; para lograr salidas tempranas se emplea el bucle Mientras con una condición compuesta lógica."
          }
        },
        {
          "@type": "Question",
          "name": "¿Cuál es la complejidad temporal de la búsqueda secuencial?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Tiene una complejidad de O(1) en el mejor de los casos (cuando el dato está en la primera casilla) y O(N) en el peor o promedio cuando se debe revisar todo el vector."
          }
        }
      ]
    }
  ]
}
</script></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Número Mayor y Menor en un Arreglo en PSeInt: Algoritmo y Diagrama</title>
		<link>https://pseint.org/mayor-menor-arreglo-pseint/</link>
		
		<dc:creator><![CDATA[El Profe Juan]]></dc:creator>
		<pubDate>Wed, 14 Oct 2026 16:27:26 +0000</pubDate>
				<category><![CDATA[Arreglos y Matrices]]></category>
		<guid isPermaLink="false">https://pseint.org/mayor-menor-arreglo-pseint/</guid>

					<description><![CDATA[Encuentra el valor máximo y mínimo de un arreglo en PSeInt en una sola pasada O(N). Diagrama de flujo DFD, rastreo de índices y prueba de escritorio.]]></description>
										<content:encoded><![CDATA[<style>
.entry-title, h1.entry-title {
    max-width: 860px !important;
    margin-left: auto !important;
    margin-right: auto !important;
    text-wrap: balance !important;
    line-height: 1.25 !important;
}
</style>
<article style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1e293b; line-height: 1.8; max-width: 100%;">
<p>    <!-- 1. HEADER METADATA BADGES --></p>
<header style="margin-bottom: 35px;">
<div style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px;">
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #e0f2fe; color: #0369a1; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 700; text-transform: uppercase; line-height: 1.2;">Nivel: Intermedio</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #f1f5f9; color: #475569; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Estructura: Arreglos (Vectores) / Bucle Para</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #fef3c7; color: #b45309; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Tipo de Dato: Entero / Real</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #ecfdf5; color: #047857; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">PSeInt: Perfil Flexible y Estricto (Base 1)</span>
        </div>
<p>        <!-- BLUF BOX (Bottom Line Up Front) --></p>
<div style="background: #f8fafc; border-left: 5px solid #2563eb; padding: 24px; border-radius: 0 10px 10px 0; box-shadow: 0 2px 4px rgba(0,0,0,0.03);">
<p style="margin: 0 0 12px 0; font-size: 1.12rem; color: #1e293b; font-weight: 600;">
                El <strong>algoritmo para hallar el número mayor y menor en un arreglo</strong> recorre una colección lineal de datos en una sola pasada con complejidad temporal óptima \(O(n)\), determinando tanto los valores extremos como las posiciones exactas (índices) donde se encuentran.
            </p>
<p style="margin: 0; font-size: 0.98rem; color: #475569;">
                <strong>Regla de oro de la inicialización:</strong> Nunca inicialices el mayor o menor en <code>0</code> ni en valores arbitrarios. La referencia inicial debe ser siempre el primer elemento real del vector (<code>mayor &lt;- v[1]</code> y <code>menor &lt;- v[1]</code>), comenzando la comparación desde la segunda posición (<code>i &lt;- 2</code>) para evitar fallos críticos ante listas con números 100% negativos o positivos.
            </p>
</p></div>
</header>
<p>    <!-- SECTION 1: THEORY & FOUNDATIONS --></p>
<h2>Fundamentos de Arreglos Unidimensionales y el Invariante de Inicialización</h2>
<p>
        Un <strong>vector o arreglo unidimensional</strong> en PSeInt es una estructura de datos homogénea y estática que almacena una secuencia contigua de elementos del mismo tipo bajo un único identificador. A diferencia de las variables escalares simples, cada celda se accede mediante un <strong>subíndice entero</strong> utilizando la sintaxis de corchetes <code>arreglo[i]</code>.
    </p>
<p>
        Para gestionar correctamente arreglos en PSeInt, es crucial comprender dos aspectos arquitectónicos fundamentales:
    </p>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 18px; margin: 25px 0;">
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #1e40af; font-size: 1.05rem;">1. Base de Indexación (1-Based Index)</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                Por defecto y en perfiles académicos estándar (como el perfil Estricto), PSeInt numera las posiciones desde <strong>1 hasta N</strong>. Si dimensionas <code>Dimension v[5]</code>, los índices válidos son <code>v[1], v[2], v[3], v[4], v[5]</code>. Intentar acceder a <code>v[0]</code> o <code>v[6]</code> disparará el clásico <a href="/error-303-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Error 303: Subíndice fuera de rango</a>.
            </p>
</p></div>
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #b45309; font-size: 1.05rem;">2. El Antipatrón de Inicializar en Cero</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                Si inicializas <code>mayor &lt;- 0</code> y el usuario ingresa temperaturas bajo cero como <code>[-12, -45, -5]</code>, el algoritmo afirmará erróneamente que el número mayor es <code>0</code>, un valor falso que ni siquiera forma parte del conjunto. Al asignar <code>v[1]</code> como pivote inicial, garantizas que los extremos pertenezcan de forma infalible al dominio de datos ingresado.
            </p>
</p></div>
</p></div>
<p>    <!-- SECTION 2: EXERCISE 1 (CORE ALGORITHM WITH INDEXES) --></p>
<h2>Ejercicio 1 Algoritmo Clásico para Hallar Mayor y Menor con Índices de Posición</h2>
<p>
        En este primer ejercicio implementaremos un algoritmo con un vector de tamaño fijo (\(N = 5\)). Solicitaremos los datos al usuario mediante un <a href="/para-hasta-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">bucle Para en PSeInt</a>, inicializaremos las variables de control con el primer elemento y registraremos simultáneamente el valor numérico y la posición exacta (índice) donde se detectó el extremo.
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Perfil Estricto y Flexible)</span><br />
            <span style="color: #38bdf8; font-size: 0.8rem; font-weight: 600;">MayorMenorVector.psc</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo MayorMenorVector
    // 1. Declaración de variables y estructura de datos
    Definir v Como Real
    Definir n, i, posMayor, posMenor Como Entero
    Definir mayor, menor Como Real
    
    n &lt;- 5
    Dimension v[5]
    
    Escribir "=== BÚSQUEDA DE MAYOR Y MENOR EN UN ARREGLO ==="
    Escribir "Ingrese los ", n, " valores numéricos:"
    
    // 2. Carga secuencial de datos en el vector
    Para i &lt;- 1 Hasta n Con Paso 1 Hacer
        Escribir "Elemento [", i, "]: "
        Leer v[i]
    FinPara
    
    // 3. Inicialización defensiva: tomar el primer elemento como referencia inicial
    mayor &lt;- v[1]
    posMayor &lt;- 1
    menor &lt;- v[1]
    posMenor &lt;- 1
    
    // 4. Comparación lineal en una sola pasada (desde el índice 2)
    Para i &lt;- 2 Hasta n Con Paso 1 Hacer
        Si v[i] &gt; mayor Entonces
            mayor &lt;- v[i]
            posMayor &lt;- i
        FinSi
        
        Si v[i] &lt; menor Entonces
            menor &lt;- v[i]
            posMenor &lt;- i
        FinSi
    FinPara
    
    // 5. Presentación de resultados
    Escribir ""
    Escribir "---------------------------------------------"
    Escribir "RESULTADOS DEL ANÁLISIS:"
    Escribir "-> Valor Mayor: ", mayor, " (Encontrado en la posición: ", posMayor, ")"
    Escribir "-> Valor Menor: ", menor, " (Encontrado en la posición: ", posMenor, ")"
    Escribir "---------------------------------------------"
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 3: FLOWCHART --></p>
<h2>Diagrama de Flujo del Algoritmo de Búsqueda de Extremos</h2>
<p>
        El siguiente <strong>diagrama de flujo DFD</strong> modela el flujo de control del algoritmo. Observa cómo la ramificación condicional se divide en dos estructuras alternativas simples e independientes dentro del ciclo iterativo, permitiendo actualizar el máximo y el mínimo sin interferencias:
    </p>
<div style="text-align: center; margin: 35px 0;">
        <img decoding="async" src="https://pseint.org/wp-content/uploads/2026/11/mayor-menor-arreglo-pseint-diagrama-flujo.png" 
             alt="Diagrama de flujo del algoritmo para hallar el mayor y menor en un arreglo en PSeInt" 
             style="max-width: 520px; width: 100%; height: auto; border-radius: 8px; box-shadow: 0 4px 14px rgba(0,0,0,0.08); border: 1px solid #e2e8f0;" 
             loading="lazy"></p>
<p style="font-size: 0.85rem; color: #64748b; margin-top: 10px;">
            Figura 1. Representación gráfica DFD: Inicialización en v[1], ciclo de evaluación desde i=2 y actualización condicional de extremos.
        </p>
</p></div>
<p>    <!-- SECTION 4: TRACE TABLE (PRUEBA DE ESCRITORIO) --></p>
<h2>Prueba de Escritorio Detallada con Casos de Prueba Críticos</h2>
<p>
        La <strong>prueba de escritorio</strong> es la técnica reina para verificar la robustez de un algoritmo matricial o de listas antes de llevarlo a producción. A continuación, trazamos 5 escenarios exhaustivos que demuestran la precisión del invariante de inicialización:
    </p>
<div style="overflow-x: auto; margin: 25px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.92rem; text-align: left; background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.02);">
<thead>
<tr style="background: #f8fafc; border-bottom: 2px solid #cbd5e1; color: #1e293b;">
<th style="padding: 12px 14px; font-weight: 700;">Caso / Vector de Entrada</th>
<th style="padding: 12px 14px; font-weight: 700;">v[1] Inicial</th>
<th style="padding: 12px 14px; font-weight: 700;">Iteraciones y Cambios</th>
<th style="padding: 12px 14px; font-weight: 700;">Mayor Detectado</th>
<th style="padding: 12px 14px; font-weight: 700;">Menor Detectado</th>
<th style="padding: 12px 14px; font-weight: 700;">Diagnóstico</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[14, 4, 28, 9, 15]</td>
<td style="padding: 12px 14px;">14 (pos 1)</td>
<td style="padding: 12px 14px;">i=2: menor&rarr;4; i=3: mayor&rarr;28; i=4,5: sin cambios</td>
<td style="padding: 12px 14px; color: #15803d; font-weight: 700;">28 (Pos 3)</td>
<td style="padding: 12px 14px; color: #b45309; font-weight: 700;">4 (Pos 2)</td>
<td style="padding: 12px 14px;">Comportamiento estándar correcto.</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background: #fef2f2;">
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[-12, -45, -3, -80, -9]</td>
<td style="padding: 12px 14px;">-12 (pos 1)</td>
<td style="padding: 12px 14px;">i=2: menor&rarr;-45; i=3: mayor&rarr;-3; i=4: menor&rarr;-80</td>
<td style="padding: 12px 14px; color: #15803d; font-weight: 700;">-3 (Pos 3)</td>
<td style="padding: 12px 14px; color: #b45309; font-weight: 700;">-80 (Pos 4)</td>
<td style="padding: 12px 14px; color: #991b1b; font-weight: 600;">Supera la trampa de números negativos.</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[7, 7, 7, 7, 7]</td>
<td style="padding: 12px 14px;">7 (pos 1)</td>
<td style="padding: 12px 14px;">Ninguna condición estricta (&gt; o &lt;) se cumple</td>
<td style="padding: 12px 14px; color: #15803d; font-weight: 700;">7 (Pos 1)</td>
<td style="padding: 12px 14px; color: #b45309; font-weight: 700;">7 (Pos 1)</td>
<td style="padding: 12px 14px;">Elementos homogéneos sin errores de bifurcación.</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[50, 40, 30, 20, 10]</td>
<td style="padding: 12px 14px;">50 (pos 1)</td>
<td style="padding: 12px 14px;">Cada iteración actualiza el menor sucesivamente</td>
<td style="padding: 12px 14px; color: #15803d; font-weight: 700;">50 (Pos 1)</td>
<td style="padding: 12px 14px; color: #b45309; font-weight: 700;">10 (Pos 5)</td>
<td style="padding: 12px 14px;">Caso ordenado decreciente verificado.</td>
</tr>
<tr>
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[12.5, -3.2, 45.8, 0.0, 45.8]</td>
<td style="padding: 12px 14px;">12.5 (pos 1)</td>
<td style="padding: 12px 14px;">i=2: menor&rarr;-3.2; i=3: mayor&rarr;45.8; i=5: no altera pos 3</td>
<td style="padding: 12px 14px; color: #15803d; font-weight: 700;">45.8 (Pos 3)</td>
<td style="padding: 12px 14px; color: #b45309; font-weight: 700;">-3.2 (Pos 2)</td>
<td style="padding: 12px 14px;">Preserva la primera ocurrencia ante duplicados.</td>
</tr>
</tbody>
</table></div>
<p>    <!-- SECTION 5: EXERCISE 2 (DYNAMIC SIZING + DEFENSIVE VALIDATION) --></p>
<h2>Ejercicio 2 Arreglo de Tamaño Dinámico con Validación Defensiva Repetir</h2>
<p>
        En aplicaciones reales, la cantidad de elementos a procesar rara vez es constante. PSeInt permite definir la dimensión de un arreglo utilizando una variable entera previamente leída (en perfiles configurados con dimensionamiento dinámico), o declarando un arreglo con una capacidad máxima reservada y operando sobre un tamaño lógico \(N\).
    </p>
<p>
        A continuación, empleamos un bucle <code>Repetir...Hasta Que</code> para validar rigurosamente que el tamaño \(N\) se encuentre entre 1 y 100, evitando que el usuario ingrese cantidades nulas o negativas:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo con Validación Robusta</span><br />
            <span style="color: #38bdf8; font-size: 0.8rem; font-weight: 600;">MayorMenorDinamico.psc</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo MayorMenorDinamico
    Definir MAX_TAM Como Entero
    MAX_TAM &lt;- 100
    
    Definir v Como Real
    Definir n, i, posMayor, posMenor Como Entero
    Definir mayor, menor, suma, promedio Como Real
    
    Dimension v[MAX_TAM]
    
    // Validación de entrada para el tamaño del vector
    Repetir
        Escribir "Ingrese la cantidad de elementos a registrar (1 a ", MAX_TAM, "): "
        Leer n
        Si n &lt; 1 O n &gt; MAX_TAM Entonces
            Escribir "ERROR: La cantidad debe estar entre 1 y ", MAX_TAM, ". Intente nuevamente."
        FinSi
    Hasta Que n &gt;= 1 Y n &lt;= MAX_TAM
    
    // Lectura de los n elementos
    Escribir "--- Entrada de Datos ---"
    Para i &lt;- 1 Hasta n Con Paso 1 Hacer
        Escribir "Valor para la posición [", i, "]: "
        Leer v[i]
    FinPara
    
    // Inicialización de extremos
    mayor &lt;- v[1]
    posMayor &lt;- 1
    menor &lt;- v[1]
    posMenor &lt;- 1
    suma &lt;- v[1]
    
    // Prospección de extremos y acumulador en un solo ciclo
    Para i &lt;- 2 Hasta n Con Paso 1 Hacer
        suma &lt;- suma + v[i]
        
        Si v[i] &gt; mayor Entonces
            mayor &lt;- v[i]
            posMayor &lt;- i
        FinSi
        
        Si v[i] &lt; menor Entonces
            menor &lt;- v[i]
            posMenor &lt;- i
        FinSi
    FinPara
    
    promedio &lt;- suma / n
    
    // Reporte consolidado
    Escribir ""
    Escribir "================ REPORTE ESTADÍSTICO ================"
    Escribir "Total de elementos evaluados : ", n
    Escribir "Elemento Mayor               : ", mayor, " (Posición ", posMayor, ")"
    Escribir "Elemento Menor               : ", menor, " (Posición ", posMenor, ")"
    Escribir "Rango de dispersión (Mayor-Menor): ", (mayor - menor)
    Escribir "Suma total acumulada         : ", suma
    Escribir "Promedio aritmético          : ", promedio
    Escribir "======================================================"
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 6: EXERCISE 3 (MODULARIZATION WITH SUBPROCESOS) --></p>
<h2>Ejercicio 3 Modularización con Subprocesos y Paso de Arreglos por Referencia</h2>
<p>
        Para proyectos de mayor envergadura o evaluaciones académicas avanzadas, la separación de responsabilidades mediante <a href="/subproceso-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">SubProcesos en PSeInt</a> es obligatoria. En PSeInt, los arreglos siempre se transmiten <strong>Por Referencia</strong> hacia los subprocesos, lo que significa que el subproceso opera directamente sobre la memoria original del vector sin duplicar datos:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Estructura Modular Profesional</span><br />
            <span style="color: #38bdf8; font-size: 0.8rem; font-weight: 600;">MayorMenorModular.psc</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">// Subproceso especializado en la lectura del vector
SubProceso CargarVector(vec Por Referencia, total Por Valor)
    Definir i Como Entero
    Para i &lt;- 1 Hasta total Con Paso 1 Hacer
        Escribir "Dato [", i, "]: "
        Leer vec[i]
    FinPara
FinSubProceso

// Subproceso que calcula los extremos y retorna resultados por referencia
SubProceso CalcularExtremos(vec Por Referencia, total Por Valor, may Por Referencia, posMay Por Referencia, men Por Referencia, posMen Por Referencia)
    Definir i Como Entero
    may &lt;- vec[1]
    posMay &lt;- 1
    men &lt;- vec[1]
    posMen &lt;- 1
    
    Para i &lt;- 2 Hasta total Con Paso 1 Hacer
        Si vec[i] &gt; may Entonces
            may &lt;- vec[i]
            posMay &lt;- i
        FinSi
        Si vec[i] &lt; men Entonces
            men &lt;- vec[i]
            posMen &lt;- i
        FinSi
    FinPara
FinSubProceso

// Algoritmo principal coordinador
Algoritmo GestionExtremosVector
    Definir datos Como Real
    Definir n, pMay, pMen Como Entero
    Definir valMayor, valMenor Como Real
    
    n &lt;- 4
    Dimension datos[4]
    
    Escribir "Cargando vector de 4 elementos..."
    CargarVector(datos, n)
    
    CalcularExtremos(datos, n, valMayor, pMay, valMenor, pMen)
    
    Escribir "Procesamiento modular completado con éxito:"
    Escribir "Valor Máximo: ", valMayor, " | Índice: ", pMay
    Escribir "Valor Mínimo: ", valMenor, " | Índice: ", pMen
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 7: COMMON ERRORS --></p>
<p>    <!-- SECTION: EJERCICIO 4 (FRECUENCIAS Y DUPLICADOS) --></p>
<h2>Ejercicio 4 Detección de Frecuencias y Ocurrencias Múltiples de Extremos</h2>
<p>
        En escenarios de análisis estadístico y procesamiento de señales, no basta con identificar qué valor es el máximo o el mínimo; con frecuencia es imprescindible saber <strong>cuántas veces se repite dicho valor</strong> y en qué posiciones del arreglo aparece.
    </p>
<p>
        Si implementamos un enfoque ingenuo de dos pasadas (primero hallar el mayor y luego contar cuántos coinciden), recorremos el vector dos veces innecesariamente. A continuación, presentamos una técnica elegante que actualiza el valor extremo y su contador de frecuencia en <strong>una sola pasada lineal $O(N)$</strong>:
    </p>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">// Algoritmo: MayorMenorConFrecuencias
// Proposito: Hallar extremos y contar ocurrencias en una sola pasada O(N)
Algoritmo MayorMenorConFrecuencias
    Definir n, i Como Entero
    Definir mayor, menor Como Real
    Definir frecMayor, frecMenor Como Entero
    
    Escribir "Ingrese la cantidad de elementos del vector:"
    Leer n
    
    Dimension v[n]
    Definir v Como Real
    
    // Lectura de los elementos
    Para i &lt;- 1 Hasta n Con Paso 1 Hacer
        Escribir "Ingrese el elemento [", i, "]:"
        Leer v[i]
    FinPara
    
    // Invariante de inicializacion
    mayor &lt;- v[1]
    frecMayor &lt;- 1
    menor &lt;- v[1]
    frecMenor &lt;- 1
    
    // Bucle de comparacion desde la segunda posicion
    Para i &lt;- 2 Hasta n Con Paso 1 Hacer
        // Evaluacion del Maximo
        Si v[i] &gt; mayor Entonces
            mayor &lt;- v[i]
            frecMayor &lt;- 1 // Reiniciar frecuencia al encontrar nuevo record
        Sino
            Si v[i] = mayor Entonces
                frecMayor &lt;- frecMayor + 1 // Acumular coincidencia
            FinSi
        FinSi
        
        // Evaluacion del Minimo
        Si v[i] &lt; menor Entonces
            menor &lt;- v[i]
            frecMenor &lt;- 1 // Reiniciar frecuencia al encontrar nuevo record
        Sino
            Si v[i] = menor Entonces
                frecMenor &lt;- frecMenor + 1 // Acumular coincidencia
            FinSi
        FinSi
    FinPara
    
    // Emision de resultados
    Limpiar Pantalla
    Escribir "=================================================="
    Escribir "REPORTE DE EXTREMOS Y FRECUENCIAS DE OCURRENCIA"
    Escribir "=================================================="
    Escribir "Valor MAYOR: ", mayor, " (Aparece ", frecMayor, " vez/veces)"
    Escribir "Valor MENOR: ", menor, " (Aparece ", frecMenor, " vez/veces)"
    Escribir "=================================================="
FinAlgoritmo</code></pre>
<p>
        Este patrón de diseño es clave en entrevistas técnicas: cuando un elemento supera al extremo actual, el contador de frecuencia se restablece a <code>1</code>; si es idéntico, simplemente se incrementa. Todo se computa en una única pasada $O(N)$ sin estructuras auxiliares de almacenamiento.
    </p>
<p>    <!-- SECTION: COMPARATIVA TECNICA --></p>
<h2>Comparativa Técnica entre Algoritmos de Búsqueda de Extremos</h2>
<p>
        Existen diversas estrategias para obtener el mayor y menor de un conjunto de datos. La siguiente matriz resume las características asintóticas, número de comparaciones e idoneidad de cada método:
    </p>
<div style="overflow-x: auto; margin: 25px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.95rem; text-align: left; background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; overflow: hidden;">
<thead>
<tr style="background: #0f172a; color: #ffffff;">
<th style="padding: 14px 16px; border-bottom: 2px solid #334155;">Estrategia Algorítmica</th>
<th style="padding: 14px 16px; border-bottom: 2px solid #334155;">Complejidad Temporal</th>
<th style="padding: 14px 16px; border-bottom: 2px solid #334155;">Comparaciones Reales</th>
<th style="padding: 14px 16px; border-bottom: 2px solid #334155;">Memoria Adicional</th>
<th style="padding: 14px 16px; border-bottom: 2px solid #334155;">Veredicto de Uso</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #f1f5f9;">
<td style="padding: 12px 16px; font-weight: 700; color: #0284c7;">Barrido Lineal Simultáneo</td>
<td style="padding: 12px 16px; color: #16a34a; font-weight: 700;">$O(N)$</td>
<td style="padding: 12px 16px;">$2(N &#8211; 1)$ en peor caso</td>
<td style="padding: 12px 16px; color: #16a34a; font-weight: 700;">$O(1)$ (In-place)</td>
<td style="padding: 12px 16px; font-weight: 600; color: #16a34a;">Estándar recomendado universal</td>
</tr>
<tr style="background: #f8fafc; border-bottom: 1px solid #f1f5f9;">
<td style="padding: 12px 16px; font-weight: 700; color: #0f172a;">Dos Pasadas Separadas</td>
<td style="padding: 12px 16px;">$O(N) + O(N)$</td>
<td style="padding: 12px 16px;">$2(N &#8211; 1)$ siempre</td>
<td style="padding: 12px 16px;">$O(1)$</td>
<td style="padding: 12px 16px; color: #64748b;">Aceptable, pero duplica accesos a RAM</td>
</tr>
<tr style="border-bottom: 1px solid #f1f5f9;">
<td style="padding: 12px 16px; font-weight: 700; color: #0f172a;">Comparación por Pares (Torneo)</td>
<td style="padding: 12px 16px; color: #16a34a; font-weight: 700;">$O(N)$</td>
<td style="padding: 12px 16px; color: #16a34a; font-weight: 700;">$\lceil 3N/2<br />
ceil &#8211; 2$</td>
<td style="padding: 12px 16px;">$O(1)$</td>
<td style="padding: 12px 16px; font-weight: 600; color: #16a34a;">Óptimo teórico para hardware masivo</td>
</tr>
<tr style="background: #f8fafc;">
<td style="padding: 12px 16px; font-weight: 700; color: #0f172a;">Ordenar el Arreglo Primero</td>
<td style="padding: 12px 16px; color: #dc2626; font-weight: 700;">$O(N^2)$ o $O(N \log N)$</td>
<td style="padding: 12px 16px; color: #dc2626;">$\sim N^2 / 2$ comparaciones</td>
<td style="padding: 12px 16px;">$O(1)$ a $O(N)$</td>
<td style="padding: 12px 16px; color: #dc2626; font-weight: 700;">Antipatrón severo (Destruye el orden)</td>
</tr>
</tbody>
</table></div>
<h2>Errores Comunes al Buscar Mayor y Menor en Arreglos de PSeInt</h2>
<p>
        Durante el desarrollo de algoritmos de ordenamiento y búsqueda en arreglos surgen fallos recurrentes diagnosticados en nuestra <a href="/errores-comunes-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Guía Maestra de Errores en PSeInt</a>:
    </p>
<div style="background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
<h3 style="color: #b91c1c; margin-top: 0; font-size: 1.05rem;">1. Error 303: Subíndice Fuera de Rango</h3>
<p style="margin: 0 0 10px 0; color: #334155;">
            <strong>Causa:</strong> Iniciar el bucle de lectura en <code>0</code> (<code>Para i &lt;- 0 Hasta n</code>) o superar el límite declarado (<code>Para i &lt;- 1 Hasta n + 1</code>). En el perfil estricto de PSeInt, cualquier acceso a un índice menor a 1 o mayor al tamaño en <code>Dimension</code> aborta la ejecución de inmediato.
        </p>
<p style="margin: 0; color: #15803d; font-weight: 600;">
            <strong>Solución:</strong> Acotar rigurosamente los límites del bucle entre <code>1</code> y <code>n</code>.
        </p>
</p></div>
<div style="background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
<h3 style="color: #b91c1c; margin-top: 0; font-size: 1.05rem;">2. Confundir el Índice de Posición con el Contenido del Arreglo</h3>
<p style="margin: 0 0 10px 0; color: #334155;">
            <strong>Causa:</strong> Comparar la variable del bucle directamente con el extremo, por ejemplo: <code>Si i &gt; mayor Entonces mayor &lt;- i</code>. Esto guarda el número de iteración (1, 2, 3&#8230;) y no el número almacenado dentro del casillero del vector.
        </p>
<p style="margin: 0; color: #15803d; font-weight: 600;">
            <strong>Solución:</strong> Usar siempre los corchetes indexadores para acceder al contenido: <code>v[i]</code>.
        </p>
</p></div>
<div style="background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
<h3 style="color: #b91c1c; margin-top: 0; font-size: 1.05rem;">3. Utilizar Si-Sino Encadenado en Lugar de Dos Condiciones Independientes</h3>
<p style="margin: 0 0 10px 0; color: #334155;">
            <strong>Causa:</strong> Estructurar la lógica como <code>Si v[i] &gt; mayor Entonces ... SiNo Si v[i] &lt; menor Entonces ...</code>. Aunque en listas con más de dos elementos distintos esto puede funcionar por exclusión mutua, si el vector tiene un único elemento o datos singulares, acoplar las condiciones dificulta el rastreo lógico y la depuración en pruebas de escritorio.
        </p>
<p style="margin: 0; color: #15803d; font-weight: 600;">
            <strong>Solución:</strong> Evaluar dos bloques independientes <code>Si...FinSi</code> para mantener una simetría transparente.
        </p>
</p></div>
<p>    <!-- SECTION 8: FAQ --></p>
<p>    <!-- SINGLE-LINE CTA CARD POSITIONED RIGHT BEFORE FAQ --></p>
<div style="background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%); border-radius: 14px; padding: 32px 28px; margin: 45px 0 35px 0; text-align: center; box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.2); border: 1px solid #334155;">
<h3 style="color: #ffffff; font-size: 1.45rem; margin-top: 0; margin-bottom: 12px; font-weight: 700;">¿Listo para dominar algoritmos avanzados con arreglos y matrices?</h3>
<p style="color: #94a3b8; font-size: 1.05rem; margin-bottom: 24px; max-width: 680px; margin-left: auto; margin-right: auto; line-height: 1.6;">
            Continúa fortaleciendo tus habilidades lógicas explorando la suma, el promedio acumulado y los algoritmos de ordenamiento vectoriales en nuestro catálogo guiado.
        </p>
<div style="display: flex; gap: 14px; justify-content: center; flex-wrap: wrap;">
            <a href="/ejercicios-resueltos/" style="display: inline-flex; align-items: center; justify-content: center; background: #2563eb; color: #ffffff; padding: 13px 26px; border-radius: 8px; font-weight: 700; text-decoration: none; font-size: 0.95rem; box-shadow: 0 4px 12px rgba(37, 99, 235, 0.35);">Explorar Catálogo de Ejercicios Resueltos</a><br />
            <a href="/promedio-arreglo-pseint/" style="display: inline-flex; align-items: center; justify-content: center; background: #334155; color: #f8fafc; padding: 13px 24px; border-radius: 8px; font-weight: 600; text-decoration: none; font-size: 0.95rem;">Ver Algoritmo del Promedio de un Arreglo</a>
        </div>
</p></div>
<h2>Preguntas Frecuentes sobre Vectores y Búsqueda de Extremos</h2>
<div style="margin: 25px 0;">
<div style="border-bottom: 1px solid #e2e8f0; padding: 18px 0;">
<h3 style="margin: 0 0 8px 0; font-size: 1.05rem; color: #1e293b;">¿Qué ocurre si el valor mayor o menor se repite varias veces en el vector?</h3>
<p style="margin: 0; color: #475569; font-size: 0.95rem;">
                Si utilizas el operador estricto <code>&gt;</code>, el algoritmo registrará la posición de la <strong>primera ocurrencia</strong> del número máximo, ignorando los duplicados posteriores. Si en su lugar utilizas el operador mayor o igual <code>&gt;=</code>, cada coincidencia actualizará el índice, registrando finalmente la <strong>última posición</strong> donde apareció el elemento.
            </p>
</p></div>
<div style="border-bottom: 1px solid #e2e8f0; padding: 18px 0;">
<h3 style="margin: 0 0 8px 0; font-size: 1.05rem; color: #1e293b;">¿Por qué el bucle de búsqueda debe comenzar en 2 y no en 1?</h3>
<p style="margin: 0; color: #475569; font-size: 0.95rem;">
                Dado que en el paso previo se asignaron <code>mayor &lt;- v[1]</code> y <code>menor &lt;- v[1]</code>, evaluar <code>v[1] &gt; v[1]</code> en la iteración 1 es matemáticamente redundante y consume ciclos innecesarios. Comenzar en <code>2</code> ahorra una comparación y respeta las mejores prácticas de optimización algorítmica.
            </p>
</p></div>
<div style="border-bottom: 1px solid #e2e8f0; padding: 18px 0;">
<h3 style="margin: 0 0 8px 0; font-size: 1.05rem; color: #1e293b;">¿Se puede calcular el mayor y menor sin utilizar arreglos en PSeInt?</h3>
<p style="margin: 0; color: #475569; font-size: 0.95rem;">
                Sí. Si únicamente requieres imprimir el valor extremo al final, puedes evaluar cada número «al vuelo» a medida que el usuario lo ingresa en un bucle simple. No obstante, almacenar los datos en un arreglo es indispensable si posteriormente necesitas calcular estadísticas como la varianza, ordenar los elementos mediante el método burbuja o reutilizar la serie en otros cálculos como la <a href="/suma-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Suma de Elementos en un Arreglo</a> o el <a href="/promedio-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Promedio de un Arreglo</a>.
            </p>
</p></div>
<div style="padding: 18px 0;">
<h3 style="margin: 0 0 8px 0; font-size: 1.05rem; color: #1e293b;">¿Cómo buscar un valor específico cualquiera en lugar del mayor o menor?</h3>
<p style="margin: 0; color: #475569; font-size: 0.95rem;">
                Para localizar un número arbitrario proporcionado por el usuario, se emplea el algoritmo de búsqueda secuencial con una bandera lógica (flag). Puedes consultar nuestra guía completa del <a href="/buscar-en-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Algoritmo para Buscar un Valor en un Arreglo en PSeInt</a>.
            </p>
</p></div>
</p></div>
<p>    <!-- 10. BOTTOM CATALOG CTA BUTTON --></p>
<div style="text-align: center; margin: 45px 0 25px 0;">
        <a href="/ejercicios-resueltos/" style="display: inline-flex; align-items: center; justify-content: center; line-height: 1.2; background-color: #2563eb; color: #ffffff; padding: 12px 28px; border-radius: 8px; text-decoration: none; font-weight: 700; font-size: 1rem; transition: background 0.2s ease-in-out;">Explorar Catálogo de Ejercicios Resueltos</a>
    </div>
</article>
<p><!-- STRUCTURED DATA (JSON-LD) --><br />
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "TechArticle",
      "headline": "Algoritmo para Encontrar el Número Mayor y Menor en un Arreglo en PSeInt",
      "description": "Aprende a encontrar el valor máximo y mínimo en un arreglo o vector en PSeInt en una sola pasada O(n), registrando posiciones exactas, previniendo errores de inicialización y con diagrama de flujo.",
      "image": "https://pseint.org/wp-content/uploads/2026/11/mayor-menor-arreglo-pseint-diagrama-flujo.png",
      "author": {
        "@type": "Person",
        "name": "Profesor PSeInt"
      },
      "inLanguage": "es",
      "dependencies": "PSeInt 2026+"
    },
    {
      "@type": "HowTo",
      "name": "Cómo Encontrar el Número Mayor y Menor en un Vector con PSeInt",
      "step": [
        {
          "@type": "HowToStep",
          "name": "Dimensionar y Leer el Vector",
          "text": "Declara el arreglo con la instrucción Dimension y lee los datos dentro de un ciclo Para desde 1 hasta N."
        },
        {
          "@type": "HowToStep",
          "name": "Inicializar Mayor y Menor con el Primer Elemento",
          "text": "Asigna v[1] a las variables mayor y menor, fijando los índices posMayor y posMenor en 1 para evitar errores con números negativos."
        },
        {
          "@type": "HowToStep",
          "name": "Recorrer el Vector desde el Índice 2",
          "text": "Ejecuta un ciclo Para desde 2 hasta N comparando cada elemento con mayor y menor mediante condiciones independientes."
        },
        {
          "@type": "HowToStep",
          "name": "Actualizar Extremos e Índices",
          "text": "Si un elemento supera a mayor, actualiza el valor y su índice; si es inferior a menor, actualiza menor y su posición."
        },
        {
          "@type": "HowToStep",
          "name": "Mostrar Resultados Finales",
          "text": "Imprime en pantalla los valores extremos encontrados y las posiciones de celda correspondientes."
        }
      ]
    },
    {
      "@type": "FAQPage",
      "mainEntity": [
        {
          "@type": "Question",
          "name": "¿Qué ocurre si el valor mayor o menor se repite varias veces en el vector?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Con el operador > se preserva la primera posición encontrada; con >= se actualizaría hasta registrar la última ocurrencia."
          }
        },
        {
          "@type": "Question",
          "name": "¿Por qué el bucle de búsqueda debe comenzar en 2 y no en 1?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Porque comparar el primer elemento consigo mismo es redundante, ahorrando una comparación innecesaria."
          }
        },
        {
          "@type": "Question",
          "name": "¿Por qué nunca se debe inicializar el mayor o menor en cero?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Porque si todos los valores ingresados son negativos (ej. -10, -50), inicializar en 0 producirá un falso resultado que no pertenece al arreglo."
          }
        }
      ]
    }
  ]
}
</script></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Algoritmo para Calcular el Promedio de un Arreglo en PSeInt: Guía y Diagrama</title>
		<link>https://pseint.org/promedio-arreglo-pseint/</link>
		
		<dc:creator><![CDATA[El Profe Juan]]></dc:creator>
		<pubDate>Wed, 14 Oct 2026 16:26:31 +0000</pubDate>
				<category><![CDATA[Arreglos y Matrices]]></category>
		<guid isPermaLink="false">https://pseint.org/promedio-arreglo-pseint/</guid>

					<description><![CDATA[Aprende a calcular el promedio de un arreglo en PSeInt paso a paso. Incluye diagrama de flujo DFD, prueba de escritorio, filtrado sobre la media y código.]]></description>
										<content:encoded><![CDATA[<style>
.entry-title, h1.entry-title {
    max-width: 860px !important;
    margin-left: auto !important;
    margin-right: auto !important;
    text-wrap: balance !important;
    line-height: 1.25 !important;
}
</style>
<article style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1e293b; line-height: 1.8; max-width: 100%;">
<p>    <!-- 1. HEADER METADATA BADGES --></p>
<header style="margin-bottom: 35px;">
<div style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px;">
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #e0f2fe; color: #0369a1; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 700; text-transform: uppercase; line-height: 1.2;">Nivel: Intermedio</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #f1f5f9; color: #475569; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Estructura: Arreglos Unidimensionales / Acumulador</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #fef3c7; color: #b45309; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Tipo de Dato: Real</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #ecfdf5; color: #047857; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">PSeInt: Compatible Estricto y Flexible</span>
        </div>
<p>        <!-- BLUF BOX (Bottom Line Up Front) --></p>
<div style="background: #f8fafc; border-left: 5px solid #2563eb; padding: 24px; border-radius: 0 10px 10px 0; box-shadow: 0 2px 4px rgba(0,0,0,0.03);">
<p style="margin: 0 0 12px 0; font-size: 1.12rem; color: #1e293b; font-weight: 600;">
                El <strong>algoritmo para calcular el promedio de un arreglo en PSeInt</strong> suma la totalidad de los elementos almacenados en un vector lineal y divide dicho acumulado entre la cantidad exacta de datos registrados (\(ar{x} = rac{1}{n}\sum_{i=1}^{n} v[i]\)).
            </p>
<p style="margin: 0; font-size: 0.98rem; color: #475569;">
                <strong>Regla de oro de tipos de datos:</strong> Aunque todos los elementos del arreglo sean enteros (por ejemplo, notas de 0 a 20), las variables <code>suma</code> y <code>promedio</code> deben declararse obligatoriamente como <code>Real</code>. De lo contrario, PSeInt y la mayoría de compiladores truncarán la división descartando la fracción decimal (ej. \(75 / 6 = 12\) en vez de \(12.5\)).
            </p>
</p></div>
</header>
<p>    <!-- SECTION 1: THEORY & DATA TYPES --></p>
<h2>Fórmula del Promedio Aritmético y el Tipo de Dato en PSeInt</h2>
<p>
        El cálculo de la media aritmética es la operación central de la estadística descriptiva básica. Tras dominar nuestro <a href="/suma-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Algoritmo para Sumar Elementos de un Arreglo en PSeInt</a>, el promedio añade una dimensión de análisis sobre el conjunto:
    </p>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 18px; margin: 25px 0;">
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #1e40af; font-size: 1.05rem;">1. División en Coma Flotante</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                Al computar <code>promedio &lt;- suma / n</code>, si ambas variables fuesen de tipo <code>Entero</code>, el resultado descartaría cualquier residuo fraccionario. Declarar <code>Definir suma, promedio Como Real</code> garantiza resultados numéricos exactos.
            </p>
</p></div>
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #b45309; font-size: 1.05rem;">2. El Poder del Doble Recorrido (Two-Pass)</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                Al conservar los datos en el arreglo en memoria, podemos hacer una <strong>primera pasada</strong> para calcular el promedio global y una <strong>segunda pasada</strong> para identificar cuántos y cuáles alumnos o muestras superaron dicho promedio.
            </p>
</p></div>
</p></div>
<p>    <!-- SECTION 2: EXERCISE 1 (CORE FIXED VECTOR AVERAGE) --></p>
<h2>Ejercicio 1 Algoritmo Clásico para Calcular el Promedio de un Arreglo</h2>
<p>
        En este primer ejercicio declaramos un vector estático de tamaño \(N = 5\). El algoritmo acumula la sumatoria en una sola pasada de lectura y calcula la media aritmética final:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Perfil Estricto y Flexible)</span><br />
            <span style="color: #38bdf8; font-size: 0.8rem; font-weight: 600;">PromedioVectorClasico.psc</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo PromedioVectorClasico
    // 1. Declaración de variables: el vector y los acumuladores deben ser reales
    Definir v Como Real
    Definir n, i Como Entero
    Definir suma, promedio Como Real
    
    n &lt;- 5
    Dimension v[5]
    
    suma &lt;- 0
    
    Escribir "=== CÁLCULO DEL PROMEDIO DE UN ARREGLO ==="
    Escribir "Ingrese las ", n, " calificaciones o mediciones:"
    
    // 2. Lectura y acumulación simultánea en O(n)
    Para i &lt;- 1 Hasta n Con Paso 1 Hacer
        Escribir "Dato [", i, "]: "
        Leer v[i]
        suma &lt;- suma + v[i]
    FinPara
    
    // 3. Cálculo de la media aritmética
    promedio &lt;- suma / n
    
    // 4. Salida de resultados
    Escribir ""
    Escribir "---------------------------------------------"
    Escribir "REPORTE ESTADÍSTICO:"
    Escribir "-> Total de elementos evaluados : ", n
    Escribir "-> Sumatoria acumulada          : ", suma
    Escribir "-> Promedio aritmético final    : ", promedio
    Escribir "---------------------------------------------"
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 3: FLOWCHART --></p>
<h2>Diagrama de Flujo del Cálculo del Promedio en un Vector</h2>
<p>
        El siguiente <strong>diagrama de flujo DFD</strong> detalla la captura secuencial, la acumulación progresiva y el bloque de división posterior al ciclo iterativo:
    </p>
<div style="text-align: center; margin: 35px 0;">
        <img decoding="async" src="https://pseint.org/wp-content/uploads/2026/11/promedio-arreglo-pseint-diagrama-flujo.png" 
             alt="Diagrama de flujo del algoritmo para calcular el promedio de un arreglo en PSeInt" 
             style="max-width: 520px; width: 100%; height: auto; border-radius: 8px; box-shadow: 0 4px 14px rgba(0,0,0,0.08); border: 1px solid #e2e8f0;" 
             loading="lazy"></p>
<p style="font-size: 0.85rem; color: #64748b; margin-top: 10px;">
            Figura 1. Representación DFD: Inicialización en cero, ciclo Para con acumulación y división final suma / n.
        </p>
</p></div>
<p>    <!-- SECTION 4: TRACE TABLE (PRUEBA DE ESCRITORIO) --></p>
<h2>Prueba de Escritorio Detallada con Casos de Prueba Estadísticos</h2>
<p>
        Verificamos el comportamiento matemático del algoritmo frente a 5 conjuntos de datos reales que evalúan enteros, decimales, números periódicos y signos mixtos:
    </p>
<div style="overflow-x: auto; margin: 25px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.92rem; text-align: left; background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.02);">
<thead>
<tr style="background: #f8fafc; border-bottom: 2px solid #cbd5e1; color: #1e293b;">
<th style="padding: 12px 14px; font-weight: 700;">Caso / Vector de Entrada</th>
<th style="padding: 12px 14px; font-weight: 700;">Tamaño (n)</th>
<th style="padding: 12px 14px; font-weight: 700;">Suma Total Acumulada</th>
<th style="padding: 12px 14px; font-weight: 700;">Operación (suma / n)</th>
<th style="padding: 12px 14px; font-weight: 700;">Promedio Resultante</th>
<th style="padding: 12px 14px; font-weight: 700;">Diagnóstico</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[15, 18, 12, 14, 16]</td>
<td style="padding: 12px 14px;">5</td>
<td style="padding: 12px 14px;">75.0</td>
<td style="padding: 12px 14px;">75.0 / 5</td>
<td style="padding: 12px 14px; color: #15803d; font-weight: 700;">15.0</td>
<td style="padding: 12px 14px;">Promedio entero exacto.</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background: #eff6ff;">
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[4.5, 3.8, 4.2, 5.0, 3.5]</td>
<td style="padding: 12px 14px;">5</td>
<td style="padding: 12px 14px;">21.0</td>
<td style="padding: 12px 14px;">21.0 / 5</td>
<td style="padding: 12px 14px; color: #1d4ed8; font-weight: 700;">4.2</td>
<td style="padding: 12px 14px;">Datos decimales continuos.</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[10, 10, 11]</td>
<td style="padding: 12px 14px;">3</td>
<td style="padding: 12px 14px;">31.0</td>
<td style="padding: 12px 14px;">31.0 / 3</td>
<td style="padding: 12px 14px; color: #b45309; font-weight: 700;">10.3333&#8230;</td>
<td style="padding: 12px 14px;">Fracción periódica preservada en Real.</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[-5, 15, -10, 20]</td>
<td style="padding: 12px 14px;">4</td>
<td style="padding: 12px 14px;">20.0</td>
<td style="padding: 12px 14px;">20.0 / 4</td>
<td style="padding: 12px 14px; color: #15803d; font-weight: 700;">5.0</td>
<td style="padding: 12px 14px;">Cancelación algebraica de signos opuestos.</td>
</tr>
<tr>
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[7.0]</td>
<td style="padding: 12px 14px;">1</td>
<td style="padding: 12px 14px;">7.0</td>
<td style="padding: 12px 14px;">7.0 / 1</td>
<td style="padding: 12px 14px; color: #64748b; font-weight: 700;">7.0</td>
<td style="padding: 12px 14px;">Caso límite unitario verificado.</td>
</tr>
</tbody>
</table></div>
<p>    <!-- SECTION 5: EXERCISE 2 (DYNAMIC SIZING + DEFENSIVE ZERO-DIVISION CHECK) --></p>
<h2>Ejercicio 2 Vector Dinámico con Validación Defensiva de Cero División</h2>
<p>
        Si el usuario intentara calcular el promedio de \(N = 0\) elementos, la computadora intentará ejecutar una <strong>división entre cero</strong> (\(0 / 0\)), generando un fallo de ejecución inmediato. Mediante la estructura <code>Repetir...Hasta Que</code>, blindamos el algoritmo asegurando que \(N \ge 1\):
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo con Protección de División por Cero</span><br />
            <span style="color: #38bdf8; font-size: 0.8rem; font-weight: 600;">PromedioVectorDinamico.psc</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo PromedioVectorDinamico
    Definir MAX_TAM Como Entero
    MAX_TAM &lt;- 50
    
    Definir v, suma, promedio Como Real
    Definir n, i Como Entero
    
    Dimension v[MAX_TAM]
    
    // Validación estricta para impedir división por cero y desbordamiento de memoria
    Repetir
        Escribir "Ingrese el número de elementos a procesar (1 a ", MAX_TAM, "): "
        Leer n
        Si n &lt; 1 O n &gt; MAX_TAM Entonces
            Escribir "ERROR: La cantidad debe ser un entero positivo entre 1 y ", MAX_TAM, "."
        FinSi
    Hasta Que n &gt;= 1 Y n &lt;= MAX_TAM
    
    suma &lt;- 0
    
    Escribir "--- Entrada de Datos ---"
    Para i &lt;- 1 Hasta n Con Paso 1 Hacer
        Escribir "Elemento [", i, "]: "
        Leer v[i]
        suma &lt;- suma + v[i]
    FinPara
    
    promedio &lt;- suma / n
    
    Escribir ""
    Escribir "Total de elementos : ", n
    Escribir "Suma acumulada     : ", suma
    Escribir "Promedio calculado : ", promedio
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 6: EXERCISE 3 (STATISTICAL ANALYSIS: ELEMENTS ABOVE AVERAGE) --></p>
<h2>Ejercicio 3 Análisis Estadístico Completo y Elementos Mayores al Promedio</h2>
<p>
        La gran ventaja de almacenar los datos en un vector (en lugar de descartarlos tras sumarlos) es que permite realizar un <strong>segundo ciclo de análisis</strong>. En este ejercicio calculamos el promedio y determinamos cuántos elementos superan la media, listándolos en pantalla:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Análisis Estadístico Avanzado de Dos Pasadas</span><br />
            <span style="color: #38bdf8; font-size: 0.8rem; font-weight: 600;">PromedioYFiltroMayores.psc</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo PromedioYFiltroMayores
    Definir v, suma, promedio Como Real
    Definir n, i, contMayores Como Entero
    
    n &lt;- 6
    Dimension v[6]
    
    suma &lt;- 0
    contMayores &lt;- 0
    
    // PASADA 1: Captura de datos y acumulación
    Escribir "Ingrese los 6 valores numéricos:"
    Para i &lt;- 1 Hasta n Con Paso 1 Hacer
        Escribir "Valor [", i, "]: "
        Leer v[i]
        suma &lt;- suma + v[i]
    FinPara
    
    promedio &lt;- suma / n
    
    // PASADA 2: Conteo y detección de elementos que superan el promedio
    Escribir ""
    Escribir "================ REPORTE COMPARATIVO ================"
    Escribir "Promedio aritmético general: ", promedio
    Escribir "Elementos que superan el promedio:"
    
    Para i &lt;- 1 Hasta n Con Paso 1 Hacer
        Si v[i] &gt; promedio Entonces
            Escribir "-> Posición [", i, "] con valor: ", v[i]
            contMayores &lt;- contMayores + 1
        FinSi
    FinPara
    
    Escribir "------------------------------------------------------"
    Escribir "Total de elementos por encima de la media: ", contMayores
    Escribir "Porcentaje superior a la media          : ", (contMayores / n) * 100, "%"
    Escribir "======================================================"
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 7: EXERCISE 4 (MODULAR FUNCTIONS & BY-REFERENCE) --></p>
<h2>Ejercicio 4 Modularización con Funciones y Paso de Vectores por Referencia</h2>
<p>
        Para un diseño de software estructurado, dividimos la responsabilidad en <a href="/subproceso-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">SubProcesos</a> de carga y <a href="/funcion-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Funciones con valor de retorno</a>:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Estructura Modular Funcional</span><br />
            <span style="color: #38bdf8; font-size: 0.8rem; font-weight: 600;">PromedioModular.psc</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">// Subproceso de llenado: opera directamente sobre la memoria original
SubProceso IngresarDatos(vec Por Referencia, total Por Valor)
    Definir i Como Entero
    Para i &lt;- 1 Hasta total Con Paso 1 Hacer
        Escribir "Calificación [", i, "]: "
        Leer vec[i]
    FinPara
FinSubProceso

// Función pura que calcula y retorna el promedio
Funcion prom &lt;- ObtenerPromedioVector(vec Por Referencia, total Por Valor)
    Definir prom, acumulador Como Real
    Definir i Como Entero
    acumulador &lt;- 0
    Para i &lt;- 1 Hasta total Con Paso 1 Hacer
        acumulador &lt;- acumulador + vec[i]
    FinPara
    prom &lt;- acumulador / total
FinFuncion

// Proceso principal orquestador
Algoritmo GestionPromedioModular
    Definir notas Como Real
    Definir cantidad Como Entero
    Definir promedioFinal Como Real
    
    cantidad &lt;- 4
    Dimension notas[4]
    
    Escribir "Cargando 4 calificaciones académicas..."
    IngresarDatos(notas, cantidad)
    
    promedioFinal &lt;- ObtenerPromedioVector(notas, cantidad)
    
    Escribir ""
    Escribir "Promedio final computado por función: ", promedioFinal
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 8: COMMON ERRORS --></p>
<h2>Errores Comunes al Calcular el Promedio de un Arreglo en PSeInt</h2>
<p>
        Al calcular promedios en arreglos suelen suscitarse errores analizados en nuestra <a href="/errores-comunes-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Guía Maestra de Errores en PSeInt</a>:
    </p>
<div style="background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
<h3 style="color: #b91c1c; margin-top: 0; font-size: 1.05rem;">1. Dividir Entre la Dimensión Máxima en Lugar de los Elementos Usados</h3>
<p style="margin: 0 0 10px 0; color: #334155;">
            <strong>Causa:</strong> Declarar <code>Dimension v[100]</code>, leer únicamente <code>n = 5</code> elementos, y luego calcular <code>promedio &lt;- suma / 100</code>. Esto diluye la media entre 95 celdas no inicializadas o vacías, produciendo un promedio absurdamente diminuto.
        </p>
<p style="margin: 0; color: #15803d; font-weight: 600;">
            <strong>Solución:</strong> Dividir siempre entre la variable lógica <code>n</code> que representa la cantidad real de datos ingresados: <code>suma / n</code>.
        </p>
</p></div>
<div style="background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
<h3 style="color: #b91c1c; margin-top: 0; font-size: 1.05rem;">2. Truncamiento Decimal por Declarar Entero</h3>
<p style="margin: 0 0 10px 0; color: #334155;">
            <strong>Causa:</strong> Definir <code>Definir promedio Como Entero</code>. Si la suma da 15 y se divide entre 2, el algoritmo asignará 7 en vez de 7.5, distorsionando promedios de notas o censos.
        </p>
<p style="margin: 0; color: #15803d; font-weight: 600;">
            <strong>Solución:</strong> Declarar siempre la variable receptora <code>promedio</code> como <code>Real</code>.
        </p>
</p></div>
<div style="background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
<h3 style="color: #b91c1c; margin-top: 0; font-size: 1.05rem;">3. Colocar el Cálculo del Promedio Dentro del Bucle Para</h3>
<p style="margin: 0 0 10px 0; color: #334155;">
            <strong>Causa:</strong> Escribir <code>promedio &lt;- suma / n</code> dentro de la iteración. Esto recalcula innecesariamente la división en cada paso antes de que la sumatoria esté completa.
        </p>
<p style="margin: 0; color: #15803d; font-weight: 600;">
            <strong>Solución:</strong> La división del promedio se ejecuta exactamente UNA VEZ, fuera y después del cierre del bucle <code>FinPara</code>.
        </p>
</p></div>
<p>    <!-- SECTION 9: FAQ --></p>
<h2>Preguntas Frecuentes sobre el Promedio de Arreglos en PSeInt</h2>
<div style="margin: 25px 0;">
<div style="border-bottom: 1px solid #e2e8f0; padding: 18px 0;">
<h3 style="margin: 0 0 8px 0; font-size: 1.05rem; color: #1e293b;">¿Cuál es la diferencia entre un promedio simple y un promedio ponderado?</h3>
<p style="margin: 0; color: #475569; font-size: 0.95rem;">
                El promedio aritmético simple asume que cada elemento posee exactamente el mismo peso o relevancia (\(1/n\)). En cambio, el promedio ponderado asigna a cada elemento un peso o porcentaje específico (como créditos universitarios o ponderación de exámenes). Puedes consultar la fórmula en nuestro <a href="/promedio-ponderado-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Algoritmo para Calcular el Promedio Ponderado en PSeInt</a>.
            </p>
</p></div>
<div style="border-bottom: 1px solid #e2e8f0; padding: 18px 0;">
<h3 style="margin: 0 0 8px 0; font-size: 1.05rem; color: #1e293b;">¿Cómo redondear el promedio a dos decimales en PSeInt?</h3>
<p style="margin: 0; color: #475569; font-size: 0.95rem;">
                Mediante la técnica de multiplicación y división escalar explicada en nuestra guía de <a href="/trunc-redondear-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">redon y trunc en PSeInt</a>: <code>promedioRedondeado &lt;- redon(promedio * 100) / 100</code>.
            </p>
</p></div>
<div style="border-bottom: 1px solid #e2e8f0; padding: 18px 0;">
<h3 style="margin: 0 0 8px 0; font-size: 1.05rem; color: #1e293b;">¿Se puede calcular el promedio de solo tres notas fijas sin usar arreglos?</h3>
<p style="margin: 0; color: #475569; font-size: 0.95rem;">
                Sí, para un número reducido y estático de variables escalares independientes es más directo emplear nuestro <a href="/calcular-promedio-3-calificaciones-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Algoritmo para Calcular el Promedio de 3 Calificaciones</a>. Los arreglos se reservan para listas dinámicas o colecciones de tamaño considerable.
            </p>
</p></div>
<div style="padding: 18px 0;">
<h3 style="margin: 0 0 8px 0; font-size: 1.05rem; color: #1e293b;">¿Cómo encontrar la nota más alta y más baja además del promedio?</h3>
<p style="margin: 0; color: #475569; font-size: 0.95rem;">
                Puedes integrar los condicionales de actualización de extremos dentro del mismo bucle de lectura como mostramos en el <a href="/mayor-menor-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Algoritmo para Encontrar el Mayor y Menor en un Arreglo en PSeInt</a>, logrando un reporte estadístico completo en un solo paso.
            </p>
</p></div>
</p></div>
<p>    <!-- 10. BOTTOM CATALOG CTA BUTTON --></p>
<div style="text-align: center; margin: 45px 0 25px 0;">
        <a href="/ejercicios-resueltos/" style="display: inline-flex; align-items: center; justify-content: center; line-height: 1.2; background-color: #2563eb; color: #ffffff; padding: 12px 28px; border-radius: 8px; text-decoration: none; font-weight: 700; font-size: 1rem; transition: background 0.2s ease-in-out;">Explorar Catálogo de Ejercicios Resueltos</a>
    </div>
</article>
<p><!-- STRUCTURED DATA (JSON-LD) --><br />
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "TechArticle",
      "headline": "Algoritmo para Calcular el Promedio de un Arreglo en PSeInt",
      "description": "Guía completa del algoritmo en PSeInt para calcular el promedio o media aritmética de un arreglo lineal, con filtro de elementos sobre la media, prueba de escritorio y diagrama de flujo.",
      "image": "https://pseint.org/wp-content/uploads/2026/11/promedio-arreglo-pseint-diagrama-flujo.png",
      "author": {
        "@type": "Person",
        "name": "Profesor PSeInt"
      },
      "inLanguage": "es",
      "dependencies": "PSeInt 2026+"
    },
    {
      "@type": "HowTo",
      "name": "Cómo Calcular el Promedio de un Arreglo en PSeInt",
      "step": [
        {
          "@type": "HowToStep",
          "name": "Definir Arreglo y Variables en Real",
          "text": "Declarar el vector con Dimension y definir las variables suma y promedio como tipo Real para evitar truncamiento decimal."
        },
        {
          "@type": "HowToStep",
          "name": "Validar la Cantidad de Elementos",
          "text": "Comprobar que n > 0 para evitar el error fatal de división entre cero."
        },
        {
          "@type": "HowToStep",
          "name": "Acumular los Valores en un Ciclo Para",
          "text": "Iterar desde 1 hasta n leyendo cada valor v[i] y sumándolo en el acumulador suma."
        },
        {
          "@type": "HowToStep",
          "name": "Calcular la Media Aritmética",
          "text": "Dividir la sumatoria entre la cantidad real de datos: promedio <- suma / n."
        },
        {
          "@type": "HowToStep",
          "name": "Presentar los Resultados",
          "text": "Imprimir la suma acumulada y el promedio aritmético mediante la instrucción Escribir."
        }
      ]
    },
    {
      "@type": "FAQPage",
      "mainEntity": [
        {
          "@type": "Question",
          "name": "¿Por qué debe declararse promedio como tipo Real?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Porque la división de dos enteros frecuentemente produce un número con parte decimal; si se declara como Entero, el resultado se trunca perdiendo precisión."
          }
        },
        {
          "@type": "Question",
          "name": "¿Por qué no se debe dividir entre la dimensión máxima del arreglo?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Porque distorsiona la media con celdas vacías no utilizadas; siempre se debe dividir entre n (los datos reales ingresados)."
          }
        },
        {
          "@type": "Question",
          "name": "¿Cómo saber cuántos elementos superaron el promedio?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Realizando un segundo ciclo Para sobre el vector en memoria y contando aquellos donde v[i] > promedio."
          }
        }
      ]
    }
  ]
}
</script></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Algoritmo para Sumar los Elementos de un Arreglo en PSeInt: Guía y Diagrama</title>
		<link>https://pseint.org/suma-arreglo-pseint/</link>
		
		<dc:creator><![CDATA[El Profe Juan]]></dc:creator>
		<pubDate>Wed, 14 Oct 2026 16:25:36 +0000</pubDate>
				<category><![CDATA[Arreglos y Matrices]]></category>
		<guid isPermaLink="false">https://pseint.org/suma-arreglo-pseint/</guid>

					<description><![CDATA[Aprende a sumar los elementos de un arreglo en PSeInt con el patrón acumulador. Diagrama de flujo DFD, prueba de escritorio, validación y código completo.]]></description>
										<content:encoded><![CDATA[<style>
.entry-title, h1.entry-title {
    max-width: 860px !important;
    margin-left: auto !important;
    margin-right: auto !important;
    text-wrap: balance !important;
    line-height: 1.25 !important;
}
</style>
<article style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #1e293b; line-height: 1.8; max-width: 100%;">
<p>    <!-- 1. HEADER METADATA BADGES --></p>
<header style="margin-bottom: 35px;">
<div style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px;">
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #e0f2fe; color: #0369a1; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 700; text-transform: uppercase; line-height: 1.2;">Nivel: Intermedio</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #f1f5f9; color: #475569; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Estructura: Arreglos Unidimensionales / Bucle Para</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #fef3c7; color: #b45309; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">Tipo de Dato: Entero / Real</span><br />
            <span style="display: inline-flex; align-items: center; justify-content: center; background-color: #ecfdf5; color: #047857; padding: 4px 12px; border-radius: 6px; font-size: 0.85rem; font-weight: 600; line-height: 1.2;">PSeInt: Compatible Estricto y Flexible</span>
        </div>
<p>        <!-- BLUF BOX (Bottom Line Up Front) --></p>
<div style="background: #f8fafc; border-left: 5px solid #2563eb; padding: 24px; border-radius: 0 10px 10px 0; box-shadow: 0 2px 4px rgba(0,0,0,0.03);">
<p style="margin: 0 0 12px 0; font-size: 1.12rem; color: #1e293b; font-weight: 600;">
                El <strong>algoritmo para sumar los elementos de un arreglo en PSeInt</strong> recorre un vector lineal de \(N\) posiciones mediante un <a href="/para-hasta-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">bucle Para</a>, totalizando cada componente en una variable acumuladora inicializada en cero (<code>suma &lt;- suma + v[i]</code>).
            </p>
<p style="margin: 0; font-size: 0.98rem; color: #475569;">
                <strong>Regla de oro del acumulador:</strong> La variable <code>suma</code> debe inicializarse obligatoriamente en <code>0</code> antes de abrir el bucle iterativo; de lo contrario, se propagará basura de memoria o se provocará un error de variable no inicializada. Declarar los datos como <code>Real</code> permite computar tanto números enteros como magnitudes con decimales.
            </p>
</p></div>
</header>
<p>    <!-- SECTION 1: THEORY & ACCUMULATOR PATTERN --></p>
<h2>Concepto de Arreglo y el Patrón del Acumulador en PSeInt</h2>
<p>
        En programación algorítmica, un <strong>vector o arreglo unidimensional</strong> permite almacenar múltiples datos homogéneos bajo un solo identificador. Para calcular la sumatoria matemática \(\sum_{i=1}^{n} v[i]\), la informática recurre al célebre <strong>Patrón Acumulador</strong>:
    </p>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 18px; margin: 25px 0;">
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #1e40af; font-size: 1.05rem;">1. El Patrón Acumulador (vs Contador)</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                Mientras que un <em>contador</em> incrementa en una constante fija (<code>c &lt;- c + 1</code>), un <em>acumulador</em> adiciona un valor variable proveniente de una celda de memoria:<br />
                <br /><strong style="font-family: monospace; color: #0f172a;">suma &lt;- suma + v[i]</strong>.<br />
                <br />Requiere siempre el elemento neutro de la suma: <code>suma &lt;- 0</code>.
            </p>
</p></div>
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.03);">
<h3 style="margin-top: 0; color: #047857; font-size: 1.05rem;">2. Conservación de Datos en Memoria</h3>
<p style="margin: 0; font-size: 0.93rem; color: #475569;">
                Aunque se puede sumar «al vuelo» sin arreglos, almacenar los valores en <code>Dimension v[N]</code> permite reutilizar la serie para calcular el <a href="/promedio-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Promedio de un Arreglo</a>, extraer el <a href="/mayor-menor-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Mayor y Menor del Vector</a> o realizar búsquedas posteriores.
            </p>
</p></div>
</p></div>
<p>    <!-- SECTION 2: EXERCISE 1 (CORE FIXED VECTOR SUM) --></p>
<h2>Ejercicio 1 Algoritmo Clásico para Sumar Elementos de un Arreglo</h2>
<p>
        En este primer ejercicio declaramos un vector estático de tamaño \(N = 5\). Solicitamos los datos al usuario en un primer recorrido y totalizamos los valores en una variable acumuladora:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo PSeInt (Perfil Estricto y Flexible)</span><br />
            <span style="color: #38bdf8; font-size: 0.8rem; font-weight: 600;">SumaVectorClasico.psc</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo SumaVectorClasico
    // 1. Declaración de variables y estructura de almacenamiento
    Definir v Como Real
    Definir n, i Como Entero
    Definir suma Como Real
    
    n &lt;- 5
    Dimension v[5]
    
    // 2. Inicialización obligatoria del acumulador con el elemento neutro
    suma &lt;- 0
    
    Escribir "=== SUMATORIA DE ELEMENTOS EN UN VECTOR ==="
    Escribir "Ingrese los ", n, " valores numéricos a totalizar:"
    
    // 3. Lectura de datos y acumulación en un solo bucle de complejidad O(n)
    Para i &lt;- 1 Hasta n Con Paso 1 Hacer
        Escribir "Ingrese el elemento [", i, "]: "
        Leer v[i]
        suma &lt;- suma + v[i]
    FinPara
    
    // 4. Salida del resultado total
    Escribir ""
    Escribir "---------------------------------------------"
    Escribir "RESULTADO CONSOLIDADO:"
    Escribir "-> Cantidad de elementos sumados : ", n
    Escribir "-> Suma total de los valores     : ", suma
    Escribir "---------------------------------------------"
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 3: FLOWCHART --></p>
<h2>Diagrama de Flujo de la Suma de Elementos de un Vector</h2>
<p>
        El siguiente <strong>diagrama de flujo DFD</strong> ilustra el ciclo de lectura y acumulación progresiva:
    </p>
<div style="text-align: center; margin: 35px 0;">
        <img decoding="async" src="https://pseint.org/wp-content/uploads/2026/11/suma-arreglo-pseint-diagrama-flujo.png" 
             alt="Diagrama de flujo del algoritmo para sumar los elementos de un arreglo en PSeInt" 
             style="max-width: 520px; width: 100%; height: auto; border-radius: 8px; box-shadow: 0 4px 14px rgba(0,0,0,0.08); border: 1px solid #e2e8f0;" 
             loading="lazy"></p>
<p style="font-size: 0.85rem; color: #64748b; margin-top: 10px;">
            Figura 1. Representación gráfica DFD: Inicialización en cero, lectura secuencial de v[i] y acumulación recursiva.
        </p>
</p></div>
<p>    <!-- SECTION 4: TRACE TABLE (PRUEBA DE ESCRITORIO) --></p>
<h2>Prueba de Escritorio Detallada con Casos de Prueba Numéricos</h2>
<p>
        Comprobamos la precisión del algoritmo trazando paso a paso 5 escenarios representativos con enteros positivos, negativos, ceros y decimales continuos:
    </p>
<div style="overflow-x: auto; margin: 25px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.92rem; text-align: left; background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.02);">
<thead>
<tr style="background: #f8fafc; border-bottom: 2px solid #cbd5e1; color: #1e293b;">
<th style="padding: 12px 14px; font-weight: 700;">Caso / Vector de Entrada</th>
<th style="padding: 12px 14px; font-weight: 700;">suma Inicial</th>
<th style="padding: 12px 14px; font-weight: 700;">Traza de Iteraciones (suma + v[i])</th>
<th style="padding: 12px 14px; font-weight: 700;">Suma Final</th>
<th style="padding: 12px 14px; font-weight: 700;">Diagnóstico</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[10, 25, 5, 40, 20]</td>
<td style="padding: 12px 14px;">0.0</td>
<td style="padding: 12px 14px;">0+10=10 &rarr; 10+25=35 &rarr; 35+5=40 &rarr; 40+40=80 &rarr; 80+20=100</td>
<td style="padding: 12px 14px; color: #15803d; font-weight: 700;">100.0</td>
<td style="padding: 12px 14px;">Suma de enteros positivos estándar.</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background: #eff6ff;">
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[15, -8, 20, -5, 3]</td>
<td style="padding: 12px 14px;">0.0</td>
<td style="padding: 12px 14px;">0+15=15 &rarr; 15-8=7 &rarr; 7+20=27 &rarr; 27-5=22 &rarr; 22+3=25</td>
<td style="padding: 12px 14px; color: #1d4ed8; font-weight: 700;">25.0</td>
<td style="padding: 12px 14px;">Manejo correcto de signos algebraicos mixtos.</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0; background: #fef2f2;">
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[-4, -12, -8, -16, -10]</td>
<td style="padding: 12px 14px;">0.0</td>
<td style="padding: 12px 14px;">-4 &rarr; -16 &rarr; -24 &rarr; -40 &rarr; -50</td>
<td style="padding: 12px 14px; color: #b91c1c; font-weight: 700;">-50.0</td>
<td style="padding: 12px 14px;">Preservación de signo negativo total.</td>
</tr>
<tr style="border-bottom: 1px solid #e2e8f0;">
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[4.5, 2.5, 8.0, 1.25, 3.75]</td>
<td style="padding: 12px 14px;">0.0</td>
<td style="padding: 12px 14px;">4.5 &rarr; 7.0 &rarr; 15.0 &rarr; 16.25 &rarr; 20.0</td>
<td style="padding: 12px 14px; color: #15803d; font-weight: 700;">20.0</td>
<td style="padding: 12px 14px;">Precisión de punto flotante sin pérdida decimal.</td>
</tr>
<tr>
<td style="padding: 12px 14px; font-family: monospace; font-weight: 600;">[0, 0, 0, 0, 0]</td>
<td style="padding: 12px 14px;">0.0</td>
<td style="padding: 12px 14px;">Acumulador inalterado en cada paso</td>
<td style="padding: 12px 14px; color: #64748b; font-weight: 700;">0.0</td>
<td style="padding: 12px 14px;">Comportamiento neutro verificado.</td>
</tr>
</tbody>
</table></div>
<p>    <!-- SECTION 5: EXERCISE 2 (DYNAMIC SIZING + VALIDATION) --></p>
<h2>Ejercicio 2 Vector Dinámico con Validación Defensiva Repetir</h2>
<p>
        En situaciones prácticas, la cantidad de datos \(N\) debe ser flexible. Utilizando la estructura <code>Repetir...Hasta Que</code>, validamos que el tamaño ingresado por el usuario no exceda la memoria dimensionada ni sea menor a 1, evitando el infame <a href="/error-303-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Error 303 en PSeInt</a>:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Pseudocódigo con Dimensión Flexible Protegida</span><br />
            <span style="color: #38bdf8; font-size: 0.8rem; font-weight: 600;">SumaVectorDinamico.psc</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo SumaVectorDinamico
    Definir MAX_TAM Como Entero
    MAX_TAM &lt;- 100
    
    Definir v, suma Como Real
    Definir n, i Como Entero
    
    Dimension v[MAX_TAM]
    
    // Validación defensiva del número de elementos
    Repetir
        Escribir "Ingrese la cantidad de números a sumar (1 a ", MAX_TAM, "): "
        Leer n
        Si n &lt; 1 O n &gt; MAX_TAM Entonces
            Escribir "ERROR: La cantidad debe estar en el rango [1, ", MAX_TAM, "]. Reintente."
        FinSi
    Hasta Que n &gt;= 1 Y n &lt;= MAX_TAM
    
    suma &lt;- 0
    
    Escribir "--- Entrada de Datos ---"
    Para i &lt;- 1 Hasta n Con Paso 1 Hacer
        Escribir "Valor [", i, "]: "
        Leer v[i]
        suma &lt;- suma + v[i]
    FinPara
    
    Escribir ""
    Escribir "Suma calculada de ", n, " valores: ", suma
    Escribir "Promedio aritmético directo: ", (suma / n)
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 6: EXERCISE 3 (CONDITIONAL SUM: EVEN VS ODD) --></p>
<h2>Ejercicio 3 Suma Condicional de Elementos Pares e Impares en un Arreglo</h2>
<p>
        Un ejercicio recurrente en exámenes universitarios es bifurcar la sumatoria según la paridad aritmética del valor almacenado, empleando el operador módulo <code>MOD</code> visto en nuestro <a href="/contar-pares-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Algoritmo para Contar Números Pares en un Arreglo</a>:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Sumatoria Condicional Bifurcada</span><br />
            <span style="color: #38bdf8; font-size: 0.8rem; font-weight: 600;">SumaParesImparesVector.psc</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">Algoritmo SumaParesImparesVector
    Definir v, n, i Como Entero
    Definir sumaPares, sumaImpares, contPares, contImpares Como Entero
    
    n &lt;- 6
    Dimension v[6]
    
    sumaPares &lt;- 0
    sumaImpares &lt;- 0
    contPares &lt;- 0
    contImpares &lt;- 0
    
    Escribir "Ingrese 6 números enteros para el análisis de paridad:"
    Para i &lt;- 1 Hasta n Con Paso 1 Hacer
        Escribir "Número [", i, "]: "
        Leer v[i]
        
        // Verificación de paridad mediante el operador residuo MOD
        Si v[i] MOD 2 = 0 Entonces
            sumaPares &lt;- sumaPares + v[i]
            contPares &lt;- contPares + 1
        SiNo
            sumaImpares &lt;- sumaImpares + v[i]
            contImpares &lt;- contImpares + 1
        FinSi
    FinPara
    
    Escribir ""
    Escribir "================ REPORTE DE SUMAS ================"
    Escribir "Cantidad de números pares   : ", contPares
    Escribir "Suma total de números pares : ", sumaPares
    Escribir "Cantidad de números impares : ", contImpares
    Escribir "Suma total de impares       : ", sumaImpares
    Escribir "Suma global absoluta        : ", (sumaPares + sumaImpares)
    Escribir "=================================================="
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 7: EXERCISE 4 (MODULAR FUNCTIONS & BY-REFERENCE) --></p>
<h2>Ejercicio 4 Modularización con Funciones y Paso de Vectores por Referencia</h2>
<p>
        Para estructurar software profesional, separamos la interfaz de captura del procesamiento analítico mediante <a href="/subproceso-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">SubProcesos</a> y <a href="/funcion-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Funciones en PSeInt</a>:
    </p>
<div style="background: #0f172a; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.15);">
<div style="background: #1e293b; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;">
            <span style="color: #94a3b8; font-size: 0.85rem; font-family: monospace;">Modularización Profesional con Retorno</span><br />
            <span style="color: #38bdf8; font-size: 0.8rem; font-weight: 600;">SumaVectorModular.psc</span>
        </div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;">// Subproceso que puebla el vector (transmitido por referencia automáticamente)
SubProceso LlenarVector(datos Por Referencia, cant Por Valor)
    Definir i Como Entero
    Para i &lt;- 1 Hasta cant Con Paso 1 Hacer
        Escribir "Elemento [", i, "]: "
        Leer datos[i]
    FinPara
FinSubProceso

// Función pura con valor de retorno que totaliza el vector
Funcion total &lt;- CalcularSumatoria(datos Por Referencia, cant Por Valor)
    Definir total Como Real
    Definir i Como Entero
    total &lt;- 0
    Para i &lt;- 1 Hasta cant Con Paso 1 Hacer
        total &lt;- total + datos[i]
    FinPara
FinFuncion

// Proceso principal orquestador
Algoritmo TestSumaVectorModular
    Definir arreglo Como Real
    Definir tam Como Entero
    Definir resultado Como Real
    
    tam &lt;- 4
    Dimension arreglo[4]
    
    Escribir "Poblando vector de 4 elementos..."
    LlenarVector(arreglo, tam)
    
    resultado &lt;- CalcularSumatoria(arreglo, tam)
    
    Escribir "Sumatoria calculada mediante función modular: ", resultado
FinAlgoritmo</code></pre>
</p></div>
<p>    <!-- SECTION 8: COMMON ERRORS --></p>
<h2>Errores Comunes al Sumar Elementos de un Arreglo en PSeInt</h2>
<p>
        Durante el trabajo con vectores y acumuladores se presentan fallos típicos analizados en nuestra <a href="/errores-comunes-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Guía Maestra de Depuración en PSeInt</a>:
    </p>
<div style="background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
<h3 style="color: #b91c1c; margin-top: 0; font-size: 1.05rem;">1. Reinicializar el Acumulador Dentro del Bucle Para</h3>
<p style="margin: 0 0 10px 0; color: #334155;">
            <strong>Causa:</strong> Colocar <code>suma &lt;- 0</code> dentro del ciclo <code>Para i &lt;- 1 Hasta n</code>. Con esto, en cada iteración la suma se resetea a cero, y al finalizar el bucle la variable solo contendrá el último elemento ingresado (<code>v[n]</code>) en lugar del total.
        </p>
<p style="margin: 0; color: #15803d; font-weight: 600;">
            <strong>Solución:</strong> Asignar <code>suma &lt;- 0</code> estrictamente ANTES de entrar al bucle iterativo.
        </p>
</p></div>
<div style="background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
<h3 style="color: #b91c1c; margin-top: 0; font-size: 1.05rem;">2. Sumar el Índice i en Vez del Contenido v[i]</h3>
<p style="margin: 0 0 10px 0; color: #334155;">
            <strong>Causa:</strong> Escribir <code>suma &lt;- suma + i</code> en lugar de <code>suma &lt;- suma + v[i]</code>. Esto sumará los números correlativos de las posiciones (1 + 2 + 3 + &#8230; + N) e ignorará por completo los datos reales ingresados por el usuario.
        </p>
<p style="margin: 0; color: #15803d; font-weight: 600;">
            <strong>Solución:</strong> Utilizar los corchetes indexadores para acceder al contenido del casillero: <code>v[i]</code>.
        </p>
</p></div>
<div style="background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 20px;">
<h3 style="color: #b91c1c; margin-top: 0; font-size: 1.05rem;">3. Error 303: Subíndice Fuera de Rango (Base 0 vs Base 1)</h3>
<p style="margin: 0 0 10px 0; color: #334155;">
            <strong>Causa:</strong> Recorrer desde 0 (<code>Para i &lt;- 0 Hasta n - 1</code>) en perfiles configurados con base 1, o superar la cota superior declarada en <code>Dimension</code>.
        </p>
<p style="margin: 0; color: #15803d; font-weight: 600;">
            <strong>Solución:</strong> Ajustar los límites del bucle entre <code>1</code> y <code>n</code>.
        </p>
</p></div>
<p>    <!-- SECTION 9: FAQ --></p>
<h2>Preguntas Frecuentes sobre la Suma de Arreglos en PSeInt</h2>
<div style="margin: 25px 0;">
<div style="border-bottom: 1px solid #e2e8f0; padding: 18px 0;">
<h3 style="margin: 0 0 8px 0; font-size: 1.05rem; color: #1e293b;">¿Es obligatorio usar dos bucles Para (uno para leer y otro para sumar)?</h3>
<p style="margin: 0; color: #475569; font-size: 0.95rem;">
                No es obligatorio. Si solo requieres la suma final, puedes acumular <code>suma &lt;- suma + v[i]</code> inmediatamente después del <code>Leer v[i]</code> dentro del mismo bucle, ahorrando tiempo de ejecución y manteniendo complejidad temporal \(O(n)\). Sin embargo, separar la lectura del cálculo es una práctica pedagógica estándar para ilustrar la persistencia de datos en memoria.
            </p>
</p></div>
<div style="border-bottom: 1px solid #e2e8f0; padding: 18px 0;">
<h3 style="margin: 0 0 8px 0; font-size: 1.05rem; color: #1e293b;">¿Cómo calcular el promedio a partir de la suma de un vector?</h3>
<p style="margin: 0; color: #475569; font-size: 0.95rem;">
                Una vez completado el bucle acumulador, divides la variable <code>suma</code> entre la cantidad de elementos \(N\): <code>promedio &lt;- suma / n</code>. Puedes consultar los detalles completos en nuestro <a href="/promedio-arreglo-pseint/" style="color: #2563eb; text-decoration: underline; font-weight: 600;">Algoritmo para Calcular el Promedio de un Arreglo en PSeInt</a>.
            </p>
</p></div>
<div style="border-bottom: 1px solid #e2e8f0; padding: 18px 0;">
<h3 style="margin: 0 0 8px 0; font-size: 1.05rem; color: #1e293b;">¿Qué ocurre si el vector está vacío (N = 0)?</h3>
<p style="margin: 0; color: #475569; font-size: 0.95rem;">
                En PSeInt, dimensionar con tamaño cero o negativo provoca un fallo de sintaxis. Por ello, en el Ejercicio 2 implementamos una validación defensiva con <code>Repetir...Hasta Que n &gt;= 1</code> para impedir vectores nulos o de tamaño negativo.
            </p>
</p></div>
<div style="padding: 18px 0;">
<h3 style="margin: 0 0 8px 0; font-size: 1.05rem; color: #1e293b;">¿Cómo sumar únicamente los números que se encuentran en posiciones pares del vector?</h3>
<p style="margin: 0; color: #475569; font-size: 0.95rem;">
                Para sumar por posición (índice par) y no por valor, puedes configurar el paso del ciclo: <code>Para i &lt;- 2 Hasta n Con Paso 2 Hacer suma &lt;- suma + v[i] FinPara</code>. Esto salta automáticamente de 2 en 2 (posiciones 2, 4, 6&#8230;) optimizando el ciclo a la mitad de iteraciones.
            </p>
</p></div>
</p></div>
<p>    <!-- 10. BOTTOM CATALOG CTA BUTTON --></p>
<div style="text-align: center; margin: 45px 0 25px 0;">
        <a href="/ejercicios-resueltos/" style="display: inline-flex; align-items: center; justify-content: center; line-height: 1.2; background-color: #2563eb; color: #ffffff; padding: 12px 28px; border-radius: 8px; text-decoration: none; font-weight: 700; font-size: 1rem; transition: background 0.2s ease-in-out;">Explorar Catálogo de Ejercicios Resueltos</a>
    </div>
</article>
<p><!-- STRUCTURED DATA (JSON-LD) --><br />
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "TechArticle",
      "headline": "Algoritmo para Sumar los Elementos de un Arreglo en PSeInt",
      "description": "Guía completa del algoritmo en PSeInt para sumar los elementos de un arreglo o vector lineal, con patrón acumulador, validación de índices, prueba de escritorio y diagrama de flujo.",
      "image": "https://pseint.org/wp-content/uploads/2026/11/suma-arreglo-pseint-diagrama-flujo.png",
      "author": {
        "@type": "Person",
        "name": "Profesor PSeInt"
      },
      "inLanguage": "es",
      "dependencies": "PSeInt 2026+"
    },
    {
      "@type": "HowTo",
      "name": "Cómo Sumar los Elementos de un Vector en PSeInt",
      "step": [
        {
          "@type": "HowToStep",
          "name": "Dimensionar el Arreglo",
          "text": "Declarar la estructura de datos con la palabra clave Dimension v[N] y definir las variables numéricas."
        },
        {
          "@type": "HowToStep",
          "name": "Inicializar el Acumulador en Cero",
          "text": "Asignar suma <- 0 antes de iniciar cualquier ciclo iterativo."
        },
        {
          "@type": "HowToStep",
          "name": "Recorrer el Vector con un Ciclo Para",
          "text": "Iterar desde el índice 1 hasta N con paso 1 leyendo cada elemento v[i]."
        },
        {
          "@type": "HowToStep",
          "name": "Acumular los Valores",
          "text": "Ejecutar la instrucción suma <- suma + v[i] en cada ciclo."
        },
        {
          "@type": "HowToStep",
          "name": "Imprimir el Total",
          "text": "Mostrar el resultado final de la sumatoria mediante la instrucción Escribir."
        }
      ]
    },
    {
      "@type": "FAQPage",
      "mainEntity": [
        {
          "@type": "Question",
          "name": "¿Por qué es obligatorio inicializar el acumulador en cero?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Porque si no se inicializa, contiene basura de memoria o dispara un error de variable no inicializada, arrojando una suma errónea."
          }
        },
        {
          "@type": "Question",
          "name": "¿Cuál es la diferencia entre sumar i y sumar v[i]?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Sumar i suma las posiciones de los casilleros (1, 2, 3...); sumar v[i] suma los datos numéricos almacenados dentro del arreglo."
          }
        },
        {
          "@type": "Question",
          "name": "¿Cómo sumar en un solo ciclo Para?",
          "acceptedAnswer": {
            "@type": "Answer",
            "text": "Colocando la lectura Leer v[i] y la acumulación suma <- suma + v[i] dentro del mismo bucle Para."
          }
        }
      ]
    }
  ]
}
</script></p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Algoritmo de Ordenamiento Burbuja en PSeInt: Guía y Diagrama</title>
		<link>https://pseint.org/ordenamiento-burbuja-pseint/</link>
		
		<dc:creator><![CDATA[El Profe Juan]]></dc:creator>
		<pubDate>Sun, 18 Jan 2026 14:27:45 +0000</pubDate>
				<category><![CDATA[Arreglos y Matrices]]></category>
		<guid isPermaLink="false">https://pseint.org/?p=681</guid>

					<description><![CDATA[📘 Nivel: Intermedio (Arreglos)⏱️ Tiempo de lectura: 6 min⚙️ Perfiles: Flexible y Estricto🔁 Complejidad: O(N²) Peor Caso / O(N) Mejor Caso Respuesta Rápida (Mecánica de la Burbuja): El ordenamiento burbuja (Bubble Sort) compara pares de elementos adyacentes a lo largo de un vector y los intercambia si están desordenados (arreglo[j] &#62; arreglo[j+1]). En cada pasada...]]></description>
										<content:encoded><![CDATA[<style>.entry-title, h1.entry-title {    max-width: 860px !important;    margin-left: auto !important;    margin-right: auto !important;    text-wrap: balance !important;    line-height: 1.25 !important;}</style>
<article style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; color: #334155; line-height: 1.8; max-width: 100%;">
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-left: 5px solid #2563eb; border-radius: 8px; padding: 22px 26px; margin-bottom: 35px;">
<div style="display: flex; gap: 10px; margin-bottom: 14px; flex-wrap: wrap; align-items: center;"><span style="display: inline-flex; align-items: center; justify-content: center; background-color: #dbeafe; color: #1e40af; padding: 4px 12px; border-radius: 20px; font-size: 0.82rem; font-weight: 700; line-height: 1.2;">📘 Nivel: Intermedio (Arreglos)</span><span style="display: inline-flex; align-items: center; justify-content: center; background-color: #ecfdf5; color: #065f46; padding: 4px 12px; border-radius: 20px; font-size: 0.82rem; font-weight: 700; line-height: 1.2;">⏱️ Tiempo de lectura: 6 min</span><span style="display: inline-flex; align-items: center; justify-content: center; background-color: #f1f5f9; color: #475569; padding: 4px 12px; border-radius: 20px; font-size: 0.82rem; font-weight: 600; line-height: 1.2;">⚙️ Perfiles: Flexible y Estricto</span><span style="display: inline-flex; align-items: center; justify-content: center; background-color: #fef3c7; color: #92400e; padding: 4px 12px; border-radius: 20px; font-size: 0.82rem; font-weight: 600; line-height: 1.2;">🔁 Complejidad: O(N²) Peor Caso / O(N) Mejor Caso</span></div>
<p style="font-size: 1.08rem; color: #1e293b; margin: 0 0 10px 0; font-weight: 500;"><strong>Respuesta Rápida (Mecánica de la Burbuja):</strong> El ordenamiento burbuja (Bubble Sort) compara pares de elementos adyacentes a lo largo de un vector y los intercambia si están desordenados (<code>arreglo[j] &gt; arreglo[j+1]</code>). En cada pasada completa, el elemento más pesado «burbujea» hasta su posición definitiva al final del arreglo. Para implementarlo en PSeInt se utilizan dos bucles <code>Para</code> anidados y una variable auxiliar de intercambio (<code>aux</code>).</p>
<p style="font-size: 0.95rem; color: #64748b; margin: 0;">A continuación encontrarás el pseudocódigo canónico, la explicación paso a paso del intercambio de tres tiempos, la prueba de escritorio con vector de muestra, el diagrama de flujo oficial (DFD) y la versión optimizada con bandera lógica.</p>
</div>
<h2 style="font-size: 1.65rem; font-weight: 800; color: #0f172a; margin: 40px 0 18px 0; border-bottom: 2px solid #f1f5f9; padding-bottom: 10px;">Código en PSeInt del Algoritmo de Ordenamiento Burbuja</h2>
<p>Este pseudocódigo implementa la versión clásica optimizada por reducción de rango (el bucle interno itera hasta <code>n - i</code> para no volver a comparar los elementos que ya quedaron ordenados al final). Es 100% compatible con los perfiles Flexible y Estricto de PSeInt:</p>
<div style="background: #1e293b; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
<div style="background: #0f172a; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;"><span style="color: #94a3b8; font-size: 0.85rem; font-weight: 600; font-family: monospace;">ordenamiento_burbuja.psc</span><span style="display: inline-flex; align-items: center; color: #38bdf8; font-size: 0.8rem; font-weight: 700; background: #0369a133; padding: 3px 8px; border-radius: 4px; line-height: 1.2;">⚡ 100% Compatible: Perfiles Flexible y Estricto</span></div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155; margin: 0;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;"><span style="color: #38bdf8; font-weight: bold;">Algoritmo</span> OrdenamientoBurbuja
<span style="color: #64748b; font-style: italic;">    // 1. Declaración de variables y dimensión del arreglo</span>
    <span style="color: #38bdf8; font-weight: bold;">Definir</span> n, i, j, aux <span style="color: #38bdf8; font-weight: bold;">Como</span> <span style="color: #38bdf8; font-weight: bold;">Entero</span>;
    <span style="color: #38bdf8; font-weight: bold;">Definir</span> arreglo <span style="color: #38bdf8; font-weight: bold;">Como</span> <span style="color: #38bdf8; font-weight: bold;">Entero</span>;
    
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "=== ALGORITMO DE ORDENAMIENTO BURBUJA ===";
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "¿Cuántos elementos desea ordenar (N)?: ";
    <span style="color: #38bdf8; font-weight: bold;">Leer</span> n;
    
    <span style="color: #38bdf8; font-weight: bold;">Dimension</span> arreglo[n];
    
<span style="color: #64748b; font-style: italic;">    // 2. Captura de elementos</span>
    <span style="color: #38bdf8; font-weight: bold;">Para</span> i <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> n <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
        <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "Ingrese el elemento #", i, ": ";
        <span style="color: #38bdf8; font-weight: bold;">Leer</span> arreglo[i];
    <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
    
<span style="color: #64748b; font-style: italic;">    // 3. Algoritmo de la Burbuja: bucles anidados</span>
    <span style="color: #38bdf8; font-weight: bold;">Para</span> i <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> n - 1 <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
        <span style="color: #38bdf8; font-weight: bold;">Para</span> j <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> n - i <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
<span style="color: #64748b; font-style: italic;">            // Si el elemento actual es mayor al siguiente, se intercambian</span>
            <span style="color: #38bdf8; font-weight: bold;">Si</span> arreglo[j] <span style="color: #e2e8f0; font-weight: bold;">&gt;</span> arreglo[j + 1] <span style="color: #38bdf8; font-weight: bold;">Entonces</span>
                aux <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> arreglo[j];
                arreglo[j] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> arreglo[j + 1];
                arreglo[j + 1] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> aux;
            <span style="color: #38bdf8; font-weight: bold;">FinSi</span>
        <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
    <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
    
<span style="color: #64748b; font-style: italic;">    // 4. Mostrar el arreglo ordenado de menor a mayor</span>
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "--------------------------------------------";
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "Arreglo ordenado en forma ascendente:";
    <span style="color: #38bdf8; font-weight: bold;">Para</span> i <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> n <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
        <span style="color: #38bdf8; font-weight: bold;">Escribir</span> <span style="color: #38bdf8; font-weight: bold;">Sin Saltar</span> arreglo[i], " ";
    <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "";
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "--------------------------------------------";
<span style="color: #38bdf8; font-weight: bold;">FinAlgoritmo</span></code></pre>
</div>
<h2 style="font-size: 1.65rem; font-weight: 800; color: #0f172a; margin: 40px 0 18px 0; border-bottom: 2px solid #f1f5f9; padding-bottom: 10px;">Explicación Paso a Paso de la Estructura Algorítmica</h2>
<p>El funcionamiento interno del algoritmo de la burbuja se sustenta en tres mecanismos clave:</p>
<ul style="margin: 18px 0 24px 24px; padding: 0;">
<li style="margin-bottom: 12px;"><strong>Dimensionamiento del Arreglo (<code>Dimension arreglo[n]</code>)</strong>: En PSeInt la estructura unidimensional (vector) se declara mediante la directiva <code>Dimension</code>. Por defecto en español, la indexación de arreglos comienza en el índice <code>1</code> y culmina en <code>n</code>.</li>
<li style="margin-bottom: 12px;"><strong>Bucle Externo de Pasadas (<code>Para i &lt;- 1 Hasta n - 1</code>)</strong>: Controla el número de pasadas globales. Un arreglo de $N$ elementos requiere a lo sumo $N &#8211; 1$ pasadas para quedar completamente ordenado, pues cuando $N &#8211; 1$ elementos están en sus puestos, el último queda automáticamente ubicado.</li>
<li style="margin-bottom: 12px;"><strong>Bucle Interno con Reducción de Frontera (<code>Para j &lt;- 1 Hasta n - i</code>)</strong>: En cada pasada $i$, el elemento más grande de la porción desordenada se desplaza hasta la posición $n &#8211; i + 1$. Al iterar solo hasta <code>n - i</code>, evitamos comparaciones redundantes contra los elementos ya fijados y prevenimos errores de desbordamiento de índice al evaluar <code>j + 1</code>.</li>
<li style="margin-bottom: 12px;"><strong>Técnica de Intercambio de Tres Tiempos (Swap con <code>aux</code>)</strong>: Para permutar dos posiciones de memoria sin destruir su contenido, se utiliza una variable auxiliar temporal: <code>aux &lt;- arreglo[j]</code> (respalda el valor original), <code>arreglo[j] &lt;- arreglo[j + 1]</code> (asigna el nuevo valor), y <code>arreglo[j + 1] &lt;- aux</code> (recupera el respaldado).</li>
</ul>
<div style="background: #fff7ed; border: 1px solid #fed7aa; border-left: 5px solid #ea580c; border-radius: 8px; padding: 22px; margin: 30px 0;">
<h3 style="font-size: 1.25rem; font-weight: 800; color: #9a3412; margin-top: 0; margin-bottom: 12px;">⚠️ El Error Clásico: Desbordamiento de Índice y Destrucción del Valor sin Auxiliar</h3>
<p style="color: #7c2d12; margin: 0 0 14px 0; font-size: 0.98rem; line-height: 1.6;">Más del 50% de los errores en exámenes de algoritmos de ordenamiento ocurren en estas dos líneas de código:</p>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 14px; margin-bottom: 16px;">
<div style="background: #ffffff; border: 1px solid #fecaca; border-radius: 6px; padding: 14px;">
<div style="color: #dc2626; font-weight: 700; margin-bottom: 6px; font-size: 0.95rem;">❌ Error 1: Bucle interno hasta N (Fuera de Rango)</div>
<div style="font-family: monospace; font-size: 0.88rem; background: #fef2f2; padding: 8px 12px; border-radius: 4px; color: #991b1b; margin-bottom: 6px; line-height: 1.5;">
<div>Para j &lt;- 1 Hasta n Hacer // ¡Grave!</div>
<div>&nbsp;&nbsp;&nbsp;&nbsp;Si arreglo[j] &gt; arreglo[j + 1] Entonces &#8230;</div>
<div>FinPara</div>
</div>
<div style="font-size: 0.85rem; color: #7f1d1d;"><strong>Consecuencia:</strong> Cuando <code>j = n</code>, la expresión <code>arreglo[j + 1]</code> intenta leer la posición <code>n + 1</code>, disparando el <em>Error 303: Subíndice fuera de rango</em> en PSeInt.</div>
</div>
<div style="background: #ffffff; border: 1px solid #fecaca; border-radius: 6px; padding: 14px;">
<div style="color: #dc2626; font-weight: 700; margin-bottom: 6px; font-size: 0.95rem;">❌ Error 2: Intercambio sin variable auxiliar</div>
<div style="font-family: monospace; font-size: 0.88rem; background: #fef2f2; padding: 8px 12px; border-radius: 4px; color: #991b1b; margin-bottom: 6px; line-height: 1.5;">
<div>arreglo[j] &lt;- arreglo[j + 1]</div>
<div>arreglo[j + 1] &lt;- arreglo[j] // ¡Se sobrescribe!</div>
</div>
<div style="font-size: 0.85rem; color: #7f1d1d;"><strong>Consecuencia:</strong> Ambos casilleros quedan con el mismo valor duplicado y el dato original se pierde para siempre.</div>
</div>
</div>
<div style="background: #ffffff; border: 1px solid #bbf7d0; border-radius: 6px; padding: 14px;">
<div style="color: #16a34a; font-weight: 700; margin-bottom: 6px; font-size: 0.95rem;">✔️ Patrón de Intercambio Canónico Correcto</div>
<div style="font-family: monospace; font-size: 0.88rem; background: #f0fdf4; padding: 8px 12px; border-radius: 4px; color: #14532d; line-height: 1.5;">
<div>aux &lt;- arreglo[j]; // 1. Guardar copia en aux</div>
<div>arreglo[j] &lt;- arreglo[j + 1]; // 2. Mover el menor a la izquierda</div>
<div>arreglo[j + 1] &lt;- aux; // 3. Restaurar el mayor en la derecha</div>
</div>
</div>
</div>
<h2 style="font-size: 1.65rem; font-weight: 800; color: #0f172a; margin: 40px 0 18px 0; border-bottom: 2px solid #f1f5f9; padding-bottom: 10px;">Prueba de Escritorio con Casos Reales</h2>
<p>Para comprobar con precisión milimétrica la mecánica de hundimiento y flotación, trazamos la memoria con un vector desordenado de 5 elementos: <strong>[5, 2, 8, 1, 3]</strong>:</p>
<div style="overflow-x: auto; margin: 24px 0;">
<table style="width: 100%; border-collapse: collapse; font-size: 0.95rem; text-align: left;">
<thead>
<tr style="background: #f1f5f9; color: #0f172a; border-bottom: 2px solid #cbd5e1;">
<th style="padding: 12px 14px; font-weight: 700;">Pasada (i)</th>
<th style="padding: 12px 14px; font-weight: 700;">Comparación (j)</th>
<th style="padding: 12px 14px; font-weight: 700;">Elementos Evaluados</th>
<th style="padding: 12px 14px; font-weight: 700;">¿Intercambio?</th>
<th style="padding: 12px 14px; font-weight: 700;">Estado del Arreglo</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom: 1px solid #f1f5f9;">
<td style="padding: 10px 14px; font-weight: 600; color: #64748b;">Inicial</td>
<td style="padding: 10px 14px;">&mdash;</td>
<td style="padding: 10px 14px;">Vector sin ordenar</td>
<td style="padding: 10px 14px; color: #64748b;">&mdash;</td>
<td style="padding: 10px 14px; font-family: monospace; font-weight: 700;">[5, 2, 8, 1, 3]</td>
</tr>
<tr style="border-bottom: 1px solid #f1f5f9; background: #f8fafc;">
<td style="padding: 10px 14px; font-weight: 600; color: #2563eb;">Pasada 1</td>
<td style="padding: 10px 14px;">j = 1</td>
<td style="padding: 10px 14px;">arr[1]=5 vs arr[2]=2</td>
<td style="padding: 10px 14px; color: #16a34a; font-weight: 600;">SÍ (5 &gt; 2)</td>
<td style="padding: 10px 14px; font-family: monospace;">[2, 5, 8, 1, 3]</td>
</tr>
<tr style="border-bottom: 1px solid #f1f5f9;">
<td style="padding: 10px 14px; font-weight: 600; color: #2563eb;">Pasada 1</td>
<td style="padding: 10px 14px;">j = 2</td>
<td style="padding: 10px 14px;">arr[2]=5 vs arr[3]=8</td>
<td style="padding: 10px 14px; color: #dc2626;">NO (5 &lt; 8)</td>
<td style="padding: 10px 14px; font-family: monospace;">[2, 5, 8, 1, 3]</td>
</tr>
<tr style="border-bottom: 1px solid #f1f5f9; background: #f8fafc;">
<td style="padding: 10px 14px; font-weight: 600; color: #2563eb;">Pasada 1</td>
<td style="padding: 10px 14px;">j = 3</td>
<td style="padding: 10px 14px;">arr[3]=8 vs arr[4]=1</td>
<td style="padding: 10px 14px; color: #16a34a; font-weight: 600;">SÍ (8 &gt; 1)</td>
<td style="padding: 10px 14px; font-family: monospace;">[2, 5, 1, 8, 3]</td>
</tr>
<tr style="border-bottom: 1px solid #f1f5f9;">
<td style="padding: 10px 14px; font-weight: 600; color: #2563eb;">Pasada 1</td>
<td style="padding: 10px 14px;">j = 4</td>
<td style="padding: 10px 14px;">arr[4]=8 vs arr[5]=3</td>
<td style="padding: 10px 14px; color: #16a34a; font-weight: 600;">SÍ (8 &gt; 3)</td>
<td style="padding: 10px 14px; font-family: monospace; font-weight: 700; color: #0284c7;">[2, 5, 1, 3, 8*] (8 asegurado)</td>
</tr>
<tr style="border-bottom: 1px solid #f1f5f9; background: #f8fafc;">
<td style="padding: 10px 14px; font-weight: 600; color: #0284c7;">Pasada 2</td>
<td style="padding: 10px 14px;">j = 1 a 3</td>
<td style="padding: 10px 14px;">5 permuta con 1 y con 3</td>
<td style="padding: 10px 14px; color: #16a34a; font-weight: 600;">2 intercambios</td>
<td style="padding: 10px 14px; font-family: monospace; font-weight: 700; color: #0284c7;">[2, 1, 3, 5*, 8*] (5 asegurado)</td>
</tr>
<tr style="border-bottom: 1px solid #f1f5f9;">
<td style="padding: 10px 14px; font-weight: 600; color: #0284c7;">Pasada 3</td>
<td style="padding: 10px 14px;">j = 1 a 2</td>
<td style="padding: 10px 14px;">2 permuta con 1</td>
<td style="padding: 10px 14px; color: #16a34a; font-weight: 600;">1 intercambio</td>
<td style="padding: 10px 14px; font-family: monospace; font-weight: 700; color: #0284c7;">[1, 2, 3*, 5*, 8*] (3 asegurado)</td>
</tr>
<tr style="background: #f0fdf4;">
<td style="padding: 10px 14px; font-weight: 700; color: #166534;">Pasada 4 (Fin)</td>
<td style="padding: 10px 14px;">j = 1</td>
<td style="padding: 10px 14px;">arr[1]=1 vs arr[2]=2</td>
<td style="padding: 10px 14px; color: #dc2626;">NO (1 &lt; 2)</td>
<td style="padding: 10px 14px; font-family: monospace; font-weight: 700; color: #16a34a;">[1, 2, 3, 5, 8] (Ordenado 100%)</td>
</tr>
</tbody>
</table>
</div>
<p><strong>Conclusión de la traza:</strong> En cada pasada $i$, el elemento máximo de la sublista desordenada queda colocado en su índice correspondiente. Al término de la pasada 4, los 5 elementos quedan ordenados en orden no decreciente.</p>
<h2 style="font-size: 1.65rem; font-weight: 800; color: #0f172a; margin: 40px 0 18px 0; border-bottom: 2px solid #f1f5f9; padding-bottom: 10px;">Versión Pro con Bandera de Parada Temprana y Modo Ascendente/Descendente</h2>
<p>La mayor debilidad teórica del método de la burbuja clásico es que siempre ejecuta las $N &#8211; 1$ pasadas, incluso si el arreglo ya quedó ordenado en las primeras vueltas. Mediante una variable booleana de control (<code>huboCambio &lt;- Falso</code>), es posible detener el algoritmo de inmediato cuando no ocurran más intercambios, logrando un mejor caso lineal de $O(N)$:</p>
<div style="background: #1e293b; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
<div style="background: #0f172a; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;"><span style="color: #94a3b8; font-size: 0.85rem; font-weight: 600; font-family: monospace;">ordenamiento_burbuja_optimizado.psc</span><span style="display: inline-flex; align-items: center; color: #38bdf8; font-size: 0.8rem; font-weight: 700; background: #0369a133; padding: 3px 8px; border-radius: 4px; line-height: 1.2;">⚡ 100% Compatible: Perfiles Flexible y Estricto</span></div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155; margin: 0;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;"><span style="color: #38bdf8; font-weight: bold;">Algoritmo</span> OrdenamientoBurbujaOptimizado
    <span style="color: #38bdf8; font-weight: bold;">Definir</span> n, i, j, aux, pasadas, opcion <span style="color: #38bdf8; font-weight: bold;">Como</span> <span style="color: #38bdf8; font-weight: bold;">Entero</span>;
    <span style="color: #38bdf8; font-weight: bold;">Definir</span> arreglo <span style="color: #38bdf8; font-weight: bold;">Como</span> <span style="color: #38bdf8; font-weight: bold;">Entero</span>;
    <span style="color: #38bdf8; font-weight: bold;">Definir</span> huboCambio <span style="color: #38bdf8; font-weight: bold;">Como</span> <span style="color: #38bdf8; font-weight: bold;">Logico</span>;
    
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "==================================================";
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "  SISTEMA OPTIMIZADO DE ORDENAMIENTO BURBUJA     ";
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "==================================================";
    
    <span style="color: #38bdf8; font-weight: bold;">Repetir</span>
        <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "Ingrese la cantidad de elementos (2 a 20): ";
        <span style="color: #38bdf8; font-weight: bold;">Leer</span> n;
        <span style="color: #38bdf8; font-weight: bold;">Si</span> n <span style="color: #e2e8f0; font-weight: bold;">&lt;</span> 2 O n <span style="color: #e2e8f0; font-weight: bold;">&gt;</span> 20 <span style="color: #38bdf8; font-weight: bold;">Entonces</span>
            <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "[AVISO] La cantidad debe estar entre 2 y 20 elementos.";
        <span style="color: #38bdf8; font-weight: bold;">FinSi</span>
    <span style="color: #38bdf8; font-weight: bold;"><span style="color: #38bdf8; font-weight: bold;">Hasta</span> <span style="color: #38bdf8; font-weight: bold;">Que</span></span> n <span style="color: #e2e8f0; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&gt;</span>=</span> 2 Y n <span style="color: #e2e8f0; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>=</span> 20;
    
    <span style="color: #38bdf8; font-weight: bold;">Dimension</span> arreglo[n];
    
<span style="color: #64748b; font-style: italic;">    // Carga interactiva de datos</span>
    <span style="color: #38bdf8; font-weight: bold;">Para</span> i <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> n <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
        <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "Elemento [", i, "]: ";
        <span style="color: #38bdf8; font-weight: bold;">Leer</span> arreglo[i];
    <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
    
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "";
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "Seleccione el tipo de ordenamiento:";
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "1. Ascendente (Menor a Mayor)";
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "2. Descendente (Mayor a Menor)";
    <span style="color: #38bdf8; font-weight: bold;">Leer</span> opcion;
    
    pasadas <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 0;
    
<span style="color: #64748b; font-style: italic;">    // Proceso de ordenamiento optimizado con bandera lógica</span>
    <span style="color: #38bdf8; font-weight: bold;">Para</span> i <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> n - 1 <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
        huboCambio <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> <span style="color: #38bdf8; font-weight: bold;">Falso</span>;
        pasadas <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> pasadas + 1;
        
        <span style="color: #38bdf8; font-weight: bold;">Para</span> j <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> n - i <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
            <span style="color: #38bdf8; font-weight: bold;">Si</span> (opcion = 1 Y arreglo[j] <span style="color: #e2e8f0; font-weight: bold;">&gt;</span> arreglo[j + 1]) O (opcion = 2 Y arreglo[j] <span style="color: #e2e8f0; font-weight: bold;">&lt;</span> arreglo[j + 1]) <span style="color: #38bdf8; font-weight: bold;">Entonces</span>
                aux <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> arreglo[j];
                arreglo[j] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> arreglo[j + 1];
                arreglo[j + 1] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> aux;
                huboCambio <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> <span style="color: #38bdf8; font-weight: bold;">Verdadero</span>;
            <span style="color: #38bdf8; font-weight: bold;">FinSi</span>
        <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
        
<span style="color: #64748b; font-style: italic;">        // Si no se realizaron intercambios en toda la pasada, el vector ya está ordenado</span>
        <span style="color: #38bdf8; font-weight: bold;">Si</span> NO huboCambio <span style="color: #38bdf8; font-weight: bold;">Entonces</span>
            i <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> n; <span style="color: #64748b; font-style: italic;">// Salida temprana del ciclo</span>
        <span style="color: #38bdf8; font-weight: bold;">FinSi</span>
    <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
    
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "";
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "RESUMEN DE AUDITORÍA:";
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "- Pasadas totales realizadas : ", pasadas, " de ", (n - 1), " máximas";
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "- Arreglo final resultante   : ";
    <span style="color: #38bdf8; font-weight: bold;">Para</span> i <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> n <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
        <span style="color: #38bdf8; font-weight: bold;">Escribir</span> <span style="color: #38bdf8; font-weight: bold;">Sin Saltar</span> "[", arreglo[i], "] ";
    <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "";
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "<span style="color: #38bdf8; font-weight: bold;">Algoritmo</span> completado con éxito.";
<span style="color: #38bdf8; font-weight: bold;">FinAlgoritmo</span></code></pre>
</div>
<h2 style="font-size: 1.65rem; font-weight: 800; color: #0f172a; margin: 40px 0 18px 0; border-bottom: 2px solid #f1f5f9; padding-bottom: 10px;">Diagrama de Flujo del Algoritmo en PSeInt</h2>
<p>En los programas de ingeniería y ciencias de la computación, el <strong>Diagrama de Flujo (DFD)</strong> es un requerimiento formal indispensable. En PSeInt puedes generar este diagrama automáticamente presionando la tecla <kbd style="background: #e2e8f0; border-radius: 3px; padding: 2px 6px; font-size: 0.85rem;">F7</kbd> o mediante el menú <em>Acciones ➔ Dibujar Diagrama de Flujo</em>.</p>
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 12px; padding: 24px; margin: 28px 0; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05);">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 18px; border-bottom: 1px solid #f1f5f9; padding-bottom: 12px; flex-wrap: wrap; gap: 8px;"><span style="font-weight: 800; color: #0f172a; font-size: 1.05rem; display: flex; align-items: center; gap: 8px;"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#2563eb" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M9 3v18"/><path d="M14 9l3 3-3 3"/></svg>Diagrama de Flujo (DFD) — Algoritmo OrdenamientoBurbuja</span><span style="background: #eff6ff; color: #1e40af; font-size: 0.75rem; font-weight: 700; padding: 4px 10px; border-radius: 20px;">Estándar PSeInt / DIN 66001</span></div>
<div style="overflow-x: auto; text-align: center; padding: 10px 0;"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 620 860" style="max-width: 100%; height: auto; min-width: 320px; display: inline-block; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;"><defs><marker id="arrow" viewBox="0 0 10 10" refX="6" refY="5" markerWidth="6" markerHeight="6" orient="auto-reverse"><path d="M 0 1 L 8 5 L 0 9 z" fill="#334155" /></marker><marker id="arrow-loop" viewBox="0 0 10 10" refX="6" refY="5" markerWidth="6" markerHeight="6" orient="auto-reverse"><path d="M 0 1 L 8 5 L 0 9 z" fill="#2563eb" /></marker><filter id="shadow" x="-5%" y="-5%" width="115%" height="115%"><feDropShadow dx="0" dy="2" stdDeviation="3" flood-color="#0f172a" flood-opacity="0.08"/></filter></defs><!-- 1. Terminal Inicio --><g filter="url(#shadow)"><rect x="210" y="15" width="200" height="42" rx="21" ry="21" fill="#e0e7ff" stroke="#4338ca" stroke-width="2" /><text x="310" y="41" text-anchor="middle" font-size="14" font-weight="700" fill="#312e81">Inicio Algoritmo</text></g><!-- Arrow to Leer --><line x1="310" y1="57" x2="310" y2="85" stroke="#334155" stroke-width="2" marker-end="url(#arrow)" /><!-- 2. Entrada: Leer n y Arreglo --><g filter="url(#shadow)"><polygon points="200,85 440,85 420,130 180,130" fill="#dcfce7" stroke="#16a34a" stroke-width="2" /><text x="310" y="112" text-anchor="middle" font-size="13" font-weight="600" fill="#14532d">Leer n ; Leer arreglo[1..n]</text></g><!-- Arrow to Inicializacion i --><line x1="310" y1="130" x2="310" y2="158" stroke="#334155" stroke-width="2" marker-end="url(#arrow)" /><!-- 3. Proceso: i <- 1 --><g filter="url(#shadow)"><rect x="220" y="158" width="180" height="40" rx="6" fill="#e0f2fe" stroke="#0284c7" stroke-width="2" /><text x="310" y="183" text-anchor="middle" font-size="13" font-weight="600" fill="#0369a1">i &lt;- 1  (Bucle Externo)</text></g><!-- Arrow to Rombo Externo --><line x1="310" y1="198" x2="310" y2="228" stroke="#334155" stroke-width="2" marker-end="url(#arrow)" /><!-- 4. Rombo de Control: i <= n - 1 --><g filter="url(#shadow)"><polygon points="310,228 440,270 310,312 180,270" fill="#fef3c7" stroke="#d97706" stroke-width="2" /><text x="310" y="275" text-anchor="middle" font-size="13" font-weight="700" fill="#78350f">i &lt;= n &#8211; 1</text></g><!-- Branch Verdadero Externo --><text x="325" y="328" font-size="12" font-weight="700" fill="#16a34a">V (Sí)</text><line x1="310" y1="312" x2="310" y2="340" stroke="#16a34a" stroke-width="2" marker-end="url(#arrow)" /><!-- 5. Proceso: j <- 1 --><g filter="url(#shadow)"><rect x="220" y="340" width="180" height="38" rx="6" fill="#e0f2fe" stroke="#0284c7" stroke-width="2" /><text x="310" y="364" text-anchor="middle" font-size="13" font-weight="600" fill="#0369a1">j &lt;- 1  (Bucle Interno)</text></g><!-- Arrow to Rombo Interno --><line x1="310" y1="378" x2="310" y2="406" stroke="#334155" stroke-width="2" marker-end="url(#arrow)" /><!-- 6. Rombo de Control: j <= n - i --><g filter="url(#shadow)"><polygon points="310,406 440,448 310,490 180,448" fill="#fef3c7" stroke="#d97706" stroke-width="2" /><text x="310" y="453" text-anchor="middle" font-size="13" font-weight="700" fill="#78350f">j &lt;= n &#8211; i</text></g><!-- Branch Verdadero Interno --><text x="325" y="506" font-size="12" font-weight="700" fill="#16a34a">V (Sí)</text><line x1="310" y1="490" x2="310" y2="520" stroke="#16a34a" stroke-width="2" marker-end="url(#arrow)" /><!-- 7. Rombo de Comparacion: arr[j] > arr[j+1] --><g filter="url(#shadow)"><polygon points="310,520 455,565 310,610 165,565" fill="#fef3c7" stroke="#d97706" stroke-width="2" /><text x="310" y="570" text-anchor="middle" font-size="12" font-weight="700" fill="#78350f">arr[j] &gt; arr[j+1]</text></g><!-- Branch Si: Intercambio --><text x="180" y="555" font-size="12" font-weight="700" fill="#16a34a">V (Sí)</text><path d="M 165 565 L 120 565 L 120 635" fill="none" stroke="#16a34a" stroke-width="2" marker-end="url(#arrow)" /><g filter="url(#shadow)"><rect x="40" y="635" width="160" height="60" rx="6" fill="#e0f2fe" stroke="#0284c7" stroke-width="2" /><text x="120" y="656" text-anchor="middle" font-size="11" font-weight="600" fill="#0369a1">aux &lt;- arr[j]</text><text x="120" y="672" text-anchor="middle" font-size="11" font-weight="600" fill="#0369a1">arr[j] &lt;- arr[j+1]</text><text x="120" y="688" text-anchor="middle" font-size="11" font-weight="600" fill="#0369a1">arr[j+1] &lt;- aux</text></g><!-- Branch No: Sin Intercambio --><text x="440" y="555" font-size="12" font-weight="700" fill="#dc2626">F (No)</text><path d="M 455 565 L 490 565 L 490 710 L 310 710" fill="none" stroke="#dc2626" stroke-width="2" /><!-- Convergencia y j <- j + 1 --><path d="M 120 695 L 120 710 L 310 710" fill="none" stroke="#334155" stroke-width="2" /><line x1="310" y1="710" x2="310" y2="728" stroke="#334155" stroke-width="2" marker-end="url(#arrow)" /><g filter="url(#shadow)"><rect x="250" y="728" width="120" height="34" rx="4" fill="#e0f2fe" stroke="#0284c7" stroke-width="1.5" /><text x="310" y="750" text-anchor="middle" font-size="12" font-weight="600" fill="#0369a1">j &lt;- j + 1</text></g><!-- Loopback j to Rombo Interno --><path d="M 250 745 L 20 745 L 20 395 L 310 395 L 310 404" fill="none" stroke="#2563eb" stroke-width="2" stroke-dasharray="4,3" marker-end="url(#arrow-loop)" /><!-- Loopback i: Falso de Rombo Interno --><text x="445" y="440" font-size="12" font-weight="700" fill="#dc2626">F</text><path d="M 440 448 L 540 448 L 540 215 L 310 215 L 310 226" fill="none" stroke="#2563eb" stroke-width="2" marker-end="url(#arrow-loop)" /><!-- Salida Final: Falso de Rombo Externo --><text x="445" y="260" font-size="12" font-weight="700" fill="#dc2626">F</text><path d="M 440 270 L 590 270 L 590 780 L 440 780" fill="none" stroke="#dc2626" stroke-width="2" marker-end="url(#arrow)" /><!-- 8. Salida: Escribir arreglo --><g filter="url(#shadow)"><polygon points="200,760 440,760 420,802 180,802" fill="#fae8ff" stroke="#a855f7" stroke-width="2" /><text x="310" y="786" text-anchor="middle" font-size="13" font-weight="600" fill="#581c87">Escribir arreglo ordenado</text></g><!-- Arrow to FinAlgoritmo --><line x1="310" y1="802" x2="310" y2="825" stroke="#334155" stroke-width="2" marker-end="url(#arrow)" /><!-- 9. Terminal FinAlgoritmo --><g filter="url(#shadow)"><rect x="210" y="825" width="200" height="30" rx="15" ry="15" fill="#e0e7ff" stroke="#4338ca" stroke-width="2" /><text x="310" y="845" text-anchor="middle" font-size="13" font-weight="700" fill="#312e81">FinAlgoritmo</text></g></svg></div>
<div style="font-size: 0.85rem; color: #64748b; text-align: center; margin-top: 14px; font-style: italic;">Estructura DFD completa: se detalla el doble bucle anidado (pasadas e iteraciones adyacentes) con la bifurcación condicional de intercambio de tres pasos.</div>
</div>
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 22px; margin: 24px 0; box-shadow: 0 1px 3px rgba(0,0,0,0.05);">
<div style="font-weight: 800; color: #0f172a; margin-bottom: 14px; font-size: 1.1rem;">Correspondencia de Símbolos DFD Oficiales en PSeInt</div>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 14px;">
<div style="background: #f8fafc; border-left: 4px solid #64748b; padding: 14px; border-radius: 6px;">
<div style="display: flex; align-items: center; gap: 8px; font-weight: 700; color: #334155; margin-bottom: 6px;"><svg width="24" height="14" viewBox="0 0 24 14"><rect x="1" y="1" width="22" height="12" rx="6" fill="#e0e7ff" stroke="#4338ca" stroke-width="1.5"/></svg>Óvalo (Terminal)</div>
<div style="font-size: 0.9rem; color: #64748b;">Delimita los puntos de <code>Inicio</code> y <code>FinAlgoritmo</code> del proceso de ordenación.</div>
</div>
<div style="background: #f0fdf4; border-left: 4px solid #16a34a; padding: 14px; border-radius: 6px;">
<div style="display: flex; align-items: center; gap: 8px; font-weight: 700; color: #166534; margin-bottom: 6px;"><svg width="24" height="14" viewBox="0 0 24 14"><polygon points="5,1 23,1 19,13 1,13" fill="#dcfce7" stroke="#16a34a" stroke-width="1.5"/></svg>Paralelogramo Verde</div>
<div style="font-size: 0.9rem; color: #64748b;">Entrada de datos: captura del tamaño del arreglo y de los valores iniciales desordenados.</div>
</div>
<div style="background: #eff6ff; border-left: 4px solid #2563eb; padding: 14px; border-radius: 6px;">
<div style="display: flex; align-items: center; gap: 8px; font-weight: 700; color: #1e40af; margin-bottom: 6px;"><svg width="24" height="14" viewBox="0 0 24 14"><rect x="1" y="1" width="22" height="12" rx="2" fill="#e0f2fe" stroke="#0284c7" stroke-width="1.5"/></svg>Rectángulo Azul</div>
<div style="font-size: 0.9rem; color: #64748b;">Proceso de intercambio: asignaciones con variable temporal (<code>aux &lt;- arr[j]</code>).</div>
</div>
<div style="background: #fefce8; border-left: 4px solid #ca8a04; padding: 14px; border-radius: 6px;">
<div style="display: flex; align-items: center; gap: 8px; font-weight: 700; color: #854d0e; margin-bottom: 6px;"><svg width="24" height="14" viewBox="0 0 24 14"><polygon points="12,1 23,7 12,13 1,7" fill="#fef3c7" stroke="#d97706" stroke-width="1.5"/></svg>Rombo de Decisión</div>
<div style="font-size: 0.9rem; color: #64748b;">Evaluación comparativa adyacente: valida si <code>arr[j] &gt; arr[j+1]</code> para disparar la permutación.</div>
</div>
</div>
</div>
<h2 style="font-size: 1.65rem; font-weight: 800; color: #0f172a; margin: 40px 0 18px 0; border-bottom: 2px solid #f1f5f9; padding-bottom: 10px;">Variante Modularizada con SubProcesos</h2>
<p>En proyectos académicos de mayor envergadura se exige modularizar el código separando la lógica de ordenación de la interfaz de visualización. En PSeInt los arreglos se transmiten a los subprocesos utilizando la cláusula <strong>Por Referencia</strong>:</p>
<div style="background: #1e293b; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
<div style="background: #0f172a; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;"><span style="color: #94a3b8; font-size: 0.85rem; font-weight: 600; font-family: monospace;">burbuja_modularizado.psc</span><span style="display: inline-flex; align-items: center; color: #38bdf8; font-size: 0.8rem; font-weight: 700; background: #0369a133; padding: 3px 8px; border-radius: 4px; line-height: 1.2;">⚡ 100% Compatible: Perfiles Flexible y Estricto</span></div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155; margin: 0;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;"><span style="color: #38bdf8; font-weight: bold;">SubProceso</span> MostrarVector(arr <span style="color: #38bdf8; font-weight: bold;">Por Referencia</span>, tam <span style="color: #38bdf8; font-weight: bold;">Por Valor</span>)
    <span style="color: #38bdf8; font-weight: bold;">Definir</span> k <span style="color: #38bdf8; font-weight: bold;">Como</span> <span style="color: #38bdf8; font-weight: bold;">Entero</span>;
    <span style="color: #38bdf8; font-weight: bold;">Para</span> k <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> tam <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
        <span style="color: #38bdf8; font-weight: bold;">Escribir</span> <span style="color: #38bdf8; font-weight: bold;">Sin Saltar</span> arr[k], "  ";
    <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "";
<span style="color: #38bdf8; font-weight: bold;">FinSubProceso</span>

<span style="color: #38bdf8; font-weight: bold;">SubProceso</span> Burbuja(arr <span style="color: #38bdf8; font-weight: bold;">Por Referencia</span>, tam <span style="color: #38bdf8; font-weight: bold;">Por Valor</span>)
    <span style="color: #38bdf8; font-weight: bold;">Definir</span> p, q, temp <span style="color: #38bdf8; font-weight: bold;">Como</span> <span style="color: #38bdf8; font-weight: bold;">Entero</span>;
    <span style="color: #38bdf8; font-weight: bold;">Para</span> p <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> tam - 1 <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
        <span style="color: #38bdf8; font-weight: bold;">Para</span> q <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> tam - p <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
            <span style="color: #38bdf8; font-weight: bold;">Si</span> arr[q] <span style="color: #e2e8f0; font-weight: bold;">&gt;</span> arr[q + 1] <span style="color: #38bdf8; font-weight: bold;">Entonces</span>
                temp <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> arr[q];
                arr[q] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> arr[q + 1];
                arr[q + 1] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> temp;
            <span style="color: #38bdf8; font-weight: bold;">FinSi</span>
        <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
    <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
<span style="color: #38bdf8; font-weight: bold;">FinSubProceso</span>

<span style="color: #38bdf8; font-weight: bold;">Algoritmo</span> BurbujaModularizado
    <span style="color: #38bdf8; font-weight: bold;">Definir</span> lista, total <span style="color: #38bdf8; font-weight: bold;">Como</span> <span style="color: #38bdf8; font-weight: bold;">Entero</span>;
    total <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 5;
    <span style="color: #38bdf8; font-weight: bold;">Dimension</span> lista[total];
    
    lista[1] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 45;
    lista[2] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 12;
    lista[3] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 89;
    lista[4] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 34;
    lista[5] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 23;
    
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "Vector inicial desordenado:";
    MostrarVector(lista, total);
    
    Burbuja(lista, total);
    
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "Vector ordenado con <span style="color: #38bdf8; font-weight: bold;">SubProceso</span>:";
    MostrarVector(lista, total);
<span style="color: #38bdf8; font-weight: bold;">FinAlgoritmo</span></code></pre>
</div>
<h2 style="font-size: 1.65rem; font-weight: 800; color: #0f172a; margin: 40px 0 18px 0; border-bottom: 2px solid #f1f5f9; padding-bottom: 10px;">Variante para Ordenamiento Alfabético de Cadenas de Texto</h2>
<p>El método de la burbuja no se limita a números enteros. En PSeInt los operadores relacionales (<code>&gt;</code> y <code>&lt;</code>) aplican comparación lexicográfica de código ASCII, permitiendo ordenar listas de nombres o palabras alfabéticamente de la A a la Z:</p>
<div style="background: #1e293b; border-radius: 10px; overflow: hidden; margin: 25px 0; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">
<div style="background: #0f172a; padding: 10px 18px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #334155;"><span style="color: #94a3b8; font-size: 0.85rem; font-weight: 600; font-family: monospace;">ordenar_nombres_burbuja.psc</span><span style="display: inline-flex; align-items: center; color: #38bdf8; font-size: 0.8rem; font-weight: 700; background: #0369a133; padding: 3px 8px; border-radius: 4px; line-height: 1.2;">⚡ 100% Compatible: Perfiles Flexible y Estricto</span></div>
<pre style="background-color: #1e293b !important; color: #f8fafc !important; padding: 22px; border-radius: 10px; overflow-x: auto; font-family: 'Consolas', 'Courier New', monospace; font-size: 0.95rem; line-height: 1.65; border: 1px solid #334155; margin: 0;"><code class="language-pseudocode" style="background: transparent !important; color: #f8fafc !important; font-family: inherit; font-size: inherit;"><span style="color: #38bdf8; font-weight: bold;">Algoritmo</span> OrdenarNombresBurbuja
<span style="color: #64748b; font-style: italic;">    // Ordenamiento alfabético de palabras mediante comparación lexicográfica</span>
    <span style="color: #38bdf8; font-weight: bold;">Definir</span> nombres <span style="color: #38bdf8; font-weight: bold;">Como</span> <span style="color: #38bdf8; font-weight: bold;">Caracter</span>;
    <span style="color: #38bdf8; font-weight: bold;">Definir</span> auxNombre <span style="color: #38bdf8; font-weight: bold;">Como</span> <span style="color: #38bdf8; font-weight: bold;">Caracter</span>;
    <span style="color: #38bdf8; font-weight: bold;">Definir</span> cant, a, b <span style="color: #38bdf8; font-weight: bold;">Como</span> <span style="color: #38bdf8; font-weight: bold;">Entero</span>;
    
    cant <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 4;
    <span style="color: #38bdf8; font-weight: bold;">Dimension</span> nombres[cant];
    
    nombres[1] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> "Carlos";
    nombres[2] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> "Ana";
    nombres[3] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> "Daniela";
    nombres[4] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> "Bernardo";
    
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "Lista original de nombres:";
    <span style="color: #38bdf8; font-weight: bold;">Para</span> a <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> cant <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
        <span style="color: #38bdf8; font-weight: bold;">Escribir</span> " - ", nombres[a];
    <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
    
    <span style="color: #38bdf8; font-weight: bold;">Para</span> a <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> cant - 1 <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
        <span style="color: #38bdf8; font-weight: bold;">Para</span> b <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> cant - a <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
            <span style="color: #38bdf8; font-weight: bold;">Si</span> nombres[b] <span style="color: #e2e8f0; font-weight: bold;">&gt;</span> nombres[b + 1] <span style="color: #38bdf8; font-weight: bold;">Entonces</span>
                auxNombre <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> nombres[b];
                nombres[b] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> nombres[b + 1];
                nombres[b + 1] <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> auxNombre;
            <span style="color: #38bdf8; font-weight: bold;">FinSi</span>
        <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
    <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
    
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "--------------------------------------------";
    <span style="color: #38bdf8; font-weight: bold;">Escribir</span> "Lista ordenada alfabéticamente (A-Z):";
    <span style="color: #38bdf8; font-weight: bold;">Para</span> a <span style="color: #fbbf24; font-weight: bold;"><span style="color: #e2e8f0; font-weight: bold;">&lt;</span>-</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hasta</span> cant <span style="color: #38bdf8; font-weight: bold;">Con Paso</span> 1 <span style="color: #38bdf8; font-weight: bold;">Hacer</span>
        <span style="color: #38bdf8; font-weight: bold;">Escribir</span> " ", a, ". ", nombres[a];
    <span style="color: #38bdf8; font-weight: bold;">FinPara</span>
<span style="color: #38bdf8; font-weight: bold;">FinAlgoritmo</span></code></pre>
</div>
<div style="background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%); border-radius: 12px; padding: 28px; margin: 40px 0; border: 1px solid #cbd5e1; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05);">
<h3 style="font-size: 1.3rem; font-weight: 800; color: #0f172a; margin: 0 0 10px 0;">🎯 ¿Qué hacer ahora que dominas este algoritmo?</h3>
<p style="margin: 0 0 20px 0; color: #475569; font-size: 0.98rem; line-height: 1.6;">Consolida tu dominio sobre vectores, matrices y modularización explorando estas guías recomendadas de nuestra plataforma:</p>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 16px;">
<div style="background: #ffffff; border: 1px solid #cbd5e1; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); position: relative;">
<div style="font-weight: 800; color: #0f172a; margin-bottom: 6px; font-size: 1.05rem;"><a href="/buscar-en-arreglo-pseint/" style="text-decoration: none; color: #2563eb;"><span style="position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 1;"></span>Búsqueda en Arreglos en PSeInt →</a></div>
<div style="font-size: 0.92rem; color: #64748b; line-height: 1.5;">El paso lógico tras ordenar: localiza elementos mediante búsqueda lineal y binaria.</div>
</div>
<div style="background: #ffffff; border: 1px solid #cbd5e1; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); position: relative;">
<div style="font-weight: 800; color: #0f172a; margin-bottom: 6px; font-size: 1.05rem;"><a href="/mayor-menor-arreglo-pseint/" style="text-decoration: none; color: #2563eb;"><span style="position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 1;"></span>Número Mayor y Menor en un Arreglo →</a></div>
<div style="font-size: 0.92rem; color: #64748b; line-height: 1.5;">Aprende a encontrar valores extremos sin necesidad de ordenar todo el vector.</div>
</div>
<div style="background: #ffffff; border: 1px solid #cbd5e1; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); position: relative;">
<div style="font-weight: 800; color: #0f172a; margin-bottom: 6px; font-size: 1.05rem;"><a href="/invertir-arreglo-pseint/" style="text-decoration: none; color: #2563eb;"><span style="position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 1;"></span>Invertir un Arreglo en PSeInt →</a></div>
<div style="font-size: 0.92rem; color: #64748b; line-height: 1.5;">Técnica de doble puntero para dar vuelta un arreglo sin gastar memoria adicional.</div>
</div>
<div style="background: #ffffff; border: 1px solid #cbd5e1; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); position: relative;">
<div style="font-weight: 800; color: #0f172a; margin-bottom: 6px; font-size: 1.05rem;"><a href="/subproceso-pseint/" style="text-decoration: none; color: #2563eb;"><span style="position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: 1;"></span>SubProcesos y Paso por Referencia →</a></div>
<div style="font-size: 0.92rem; color: #64748b; line-height: 1.5;">Modulariza algoritmos complejos pasando arreglos entre funciones de forma limpia.</div>
</div>
</div>
</div>
<h2 style="font-size: 1.65rem; font-weight: 800; color: #0f172a; margin: 40px 0 18px 0; border-bottom: 2px solid #f1f5f9; padding-bottom: 10px;">Preguntas Frecuentes sobre el Método de la Burbuja en PSeInt</h2>
<div itemscope itemtype="https://schema.org/FAQPage">
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.02);" itemscope itemprop="mainEntity" itemtype="https://schema.org/Question">
<h3 style="font-size: 1.12rem; font-weight: 700; color: #0f172a; margin: 0 0 8px 0;" itemprop="name">¿Por qué el bucle interno itera hasta n &#8211; i y no hasta n &#8211; 1?</h3>
<div itemscope itemprop="acceptedAnswer" itemtype="https://schema.org/Answer">
<div style="color: #475569; font-size: 0.96rem; line-height: 1.6;" itemprop="text">Porque en cada pasada $i$, el elemento más grande de la sección evaluada queda colocado definitivamente en la posición $n &#8211; i + 1$. Iterar hasta <code>n - i</code> reduce las comparaciones a la mitad y evita evaluar elementos que ya están en su lugar final.</div>
</div>
</div>
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.02);" itemscope itemprop="mainEntity" itemtype="https://schema.org/Question">
<h3 style="font-size: 1.12rem; font-weight: 700; color: #0f172a; margin: 0 0 8px 0;" itemprop="name">¿Cómo se cambia el algoritmo para ordenar de mayor a menor (descendente)?</h3>
<div itemscope itemprop="acceptedAnswer" itemtype="https://schema.org/Answer">
<div style="color: #475569; font-size: 0.96rem; line-height: 1.6;" itemprop="text">Basta con invertir el operador de comparación condicional: cambiar <code>Si arreglo[j] &gt; arreglo[j + 1]</code> por <code>Si arreglo[j] &lt; arreglo[j + 1]</code>. De este modo, los elementos menores se desplazarán hacia el final, dejando los mayores al principio.</div>
</div>
</div>
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.02);" itemscope itemprop="mainEntity" itemtype="https://schema.org/Question">
<h3 style="font-size: 1.12rem; font-weight: 700; color: #0f172a; margin: 0 0 8px 0;" itemprop="name">¿Por qué el método de la burbuja rara vez se usa en software profesional?</h3>
<div itemscope itemprop="acceptedAnswer" itemtype="https://schema.org/Answer">
<div style="color: #475569; font-size: 0.96rem; line-height: 1.6;" itemprop="text">Debido a su complejidad cuadrática $O(N^2)$. Para arreglos de gran escala (como 100,000 registros), la burbuja requeriría cerca de 10,000 millones de operaciones, mientras que algoritmos modernos como QuickSort o MergeSort ($O(N \log N)$) lo resuelven en fracciones de segundo.</div>
</div>
</div>
<div style="background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.02);" itemscope itemprop="mainEntity" itemtype="https://schema.org/Question">
<h3 style="font-size: 1.12rem; font-weight: 700; color: #0f172a; margin: 0 0 8px 0;" itemprop="name">¿Qué ventaja tiene la optimización con bandera lógica (huboCambio)?</h3>
<div itemscope itemprop="acceptedAnswer" itemtype="https://schema.org/Answer">
<div style="color: #475569; font-size: 0.96rem; line-height: 1.6;" itemprop="text">Permite detectar si el vector ya se encuentra ordenado. Si en una pasada completa no se produce ningún intercambio, el bucle se interrumpe de inmediato, logrando una complejidad en el mejor de los casos de $O(N)$ en lugar de realizar todas las pasadas inútilmente.</div>
</div>
</div>
</div>
<div style="background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-top: 35px; display: flex; align-items: center; gap: 16px;">
<div style="background: #2563eb; color: #ffffff; width: 48px; height: 48px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 800; font-size: 1.2rem; flex-shrink: 0;">✓</div>
<div>
<div style="font-weight: 700; color: #0f172a; font-size: 0.95rem; margin-bottom: 2px;">Equipo Docente de PSeInt.org &mdash; Validación Técnica</div>
<div style="color: #64748b; font-size: 0.88rem; line-height: 1.5;">Algoritmo probado y certificado en laboratorio con las versiones oficiales de PSeInt. Verificado frente a errores de desbordamiento de índice y validado en perfiles Flexible y Estricto.</div>
</div>
</div>
</article>
<p><script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "TechArticle", "headline": "Algoritmo de Ordenamiento Burbuja en PSeInt: Guía y Diagrama", "description": "Aprende a implementar el ordenamiento burbuja en PSeInt paso a paso. Código fuente ascendente y descendente, optimización con bandera, diagrama de flujo y traza.", "url": "https://pseint.org/ordenamiento-burbuja-pseint/", "datePublished": "2024-03-01T00:00:00+00:00", "dateModified": "2026-11-07T02:30:00+00:00", "author": {"@type": "Organization", "name": "Equipo Docente de PSeInt.org", "url": "https://pseint.org"}, "publisher": {"@type": "Organization", "name": "PSeInt.org", "url": "https://pseint.org"}, "inLanguage": "es", "proficiencyLevel": "Intermediate"}, {"@type": "HowTo", "name": "Cómo ordenar un arreglo con el método burbuja en PSeInt", "description": "Instrucciones paso a paso para implementar el ordenamiento de arreglos con bucles anidados e intercambio en PSeInt.", "step": [{"@type": "HowToStep", "name": "Definir y dimensionar el arreglo", "text": "Declarar las variables enteras y dimensionar el vector con Dimension arreglo[n]."}, {"@type": "HowToStep", "name": "Implementar bucles anidados de comparación", "text": "Estructurar el bucle externo Para i <- 1 Hasta n - 1 y el bucle interno Para j <- 1 Hasta n - i."}, {"@type": "HowToStep", "name": "Efectuar intercambio de valores adyacentes", "text": "Si arreglo[j] > arreglo[j+1], realizar la permutación con la variable auxiliar aux."}]}, {"@type": "FAQPage", "mainEntity": [{"@type": "Question", "name": "¿Por qué el bucle interno itera hasta n - i y no hasta n - 1?", "acceptedAnswer": {"@type": "Answer", "text": "Porque en cada pasada el elemento mayor ya queda ubicado al final, evitando comparaciones redundantes."}}, {"@type": "Question", "name": "¿Cómo se cambia el algoritmo para ordenar de mayor a menor (descendente)?", "acceptedAnswer": {"@type": "Answer", "text": "Basta con invertir el operador de comparación condicional de mayor que (>) a menor que (<)."}}, {"@type": "Question", "name": "¿Por qué el método de la burbuja rara vez se usa en software profesional?", "acceptedAnswer": {"@type": "Answer", "text": "Por su costo computacional O(N^2), el cual resulta ineficiente para grandes volúmenes de datos frente a QuickSort o MergeSort."}}, {"@type": "Question", "name": "¿Qué ventaja tiene la optimización con bandera lógica (huboCambio)?", "acceptedAnswer": {"@type": "Answer", "text": "Permite cortar la ejecución tempranamente si el vector ya está ordenado, reduciendo el mejor caso a O(N)."}}]}]}</script></p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
