Оптимизация программы и полный код
Теперь, когда у нас есть работающая программа, оптимизируем ее, объединив поиск как наибольшего, так и наименьшего элементов в один цикл. Это более эффективно, так как нам нужно пройти по массиву только один раз вместо двух.
Откройте файл main.c
и замените весь его контент на следующую оптимизированную версию:
#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;
}
Эта оптимизированная версия:
- Использует один цикл для поиска как наибольшего, так и наименьшего элементов, что делает программу более эффективной.
- Инициализирует как
largest
, так и smallest
первым элементом массива.
- Добавляет вычисление диапазона (разности между наибольшим и наименьшим значениями).
Скомпилируем и запустим нашу оптимизированную программу:
gcc main.c -o main
./main
Введите размер массива и его элементы, как и раньше. Например, если вы введете значения 10, 25, 5, 17 и 9, вы должны увидеть вывод, похожий на следующий:
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
Эта оптимизированная версия дает те же результаты, что и раньше, но более эффективна и содержит дополнительную информацию о диапазоне значений.
При работе с большими массивами эти улучшения эффективности могут значительно сократить время вычислений, что является важным фактором при программировании.