Optimización del programa y código completo
Ahora que tenemos un programa funcional, optimicémoslo combinando la búsqueda de los elementos más grande y más pequeño en un solo bucle. Esto es más eficiente ya que solo necesitamos recorrer la matriz una vez en lugar de dos veces.
Abre el archivo main.c
y reemplaza todo su contenido con la siguiente versión optimizada:
#include <stdio.h>
int main() {
// We'll declare an array with a maximum capacity of 50 elements
int array[50];
// Variables to store the size of the array and loop counter
int size, i;
// Variables to store the largest and smallest elements
int largest, smallest;
printf("Finding Largest and Smallest Elements in an Array\n");
printf("------------------------------------------------\n\n");
// Ask user for the size of the array
printf("Enter the size of the array (max 50): ");
scanf("%d", &size);
// Validate the input size
if (size <= 0 || size > 50) {
printf("Invalid array size. Please enter a size between 1 and 50.\n");
return 1;
}
// Get array elements from the user
printf("\nEnter %d elements of the array:\n", size);
for (i = 0; i < size; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &array[i]);
}
// Display the entered array
printf("\nThe array you entered is: [ ");
for (i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("]\n\n");
// Initialize largest and smallest with the first element
largest = smallest = array[0];
// Find both the largest and smallest elements in a single pass
printf("Searching for largest and smallest elements...\n");
for (i = 1; i < size; i++) {
// Check for largest
if (array[i] > largest) {
largest = array[i];
printf("New largest found at position %d: %d\n", i + 1, largest);
}
// Check for smallest
if (array[i] < smallest) {
smallest = array[i];
printf("New smallest found at position %d: %d\n", i + 1, smallest);
}
}
// Display results
printf("\nResults:\n");
printf("- The largest element in the array is: %d\n", largest);
printf("- The smallest element in the array is: %d\n", smallest);
// Calculate and display the range
printf("- The range (difference between largest and smallest) is: %d\n", largest - smallest);
return 0;
}
Esta versión optimizada:
- Utiliza un solo bucle para encontrar tanto el elemento más grande como el más pequeño, lo que hace que el programa sea más eficiente.
- Inicializa tanto
largest
como smallest
al primer elemento de la matriz.
- Agrega un cálculo para el rango (la diferencia entre los valores más grande y más pequeño).
Compilémos y ejecutemos nuestro programa optimizado:
gcc main.c -o main
./main
Ingresa el tamaño y los elementos de la matriz como antes. Por ejemplo, si ingresas los valores 10, 25, 5, 17 y 9, deberías ver una salida similar a:
Finding Largest and Smallest Elements in an Array
------------------------------------------------
Enter the size of the array (max 50): 5
Enter 5 elements of the array:
Element 1: 10
Element 2: 25
Element 3: 5
Element 4: 17
Element 5: 9
The array you entered is: [ 10 25 5 17 9 ]
Searching for largest and smallest elements...
New largest found at position 2: 25
New smallest found at position 3: 5
Results:
- The largest element in the array is: 25
- The smallest element in the array is: 5
- The range (difference between largest and smallest) is: 20
Esta versión optimizada proporciona los mismos resultados que antes, pero es más eficiente e incluye información adicional sobre el rango de valores.
Al trabajar con matrices grandes, estas mejoras de eficiencia pueden reducir significativamente el tiempo de cálculo, lo cual es una consideración importante en la programación.