Grupo
Algoritmos de Búsqueda y Ordenación en C++
Ojetivo
Escriba un programa en C++ que utilice una función para realizar una búsqueda secuencial del número más pequeño en un array. La función debe recorrer todos los elementos, compararlos y devolver el valor más pequeño encontrado. En la función principal, defina un array de ejemplo, invoque la función y muestre el resultado.
Cree un programa que busque el número más pequeño en un array mediante búsqueda secuencial.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the input-output stream library
using namespace std;
// Function to find the smallest number using sequential search
int findSmallest(int arr[], int size) {
int smallest = arr[0]; // Assume the first element is the smallest
// Loop through the array to find the smallest element
for (int i = 1; i < size; i++) {
if (arr[i] < smallest) {
smallest = arr[i]; // Update smallest if a smaller value is found
}
}
return smallest; // Return the smallest value found
}
int main() {
// Define an array of integers
int numbers[] = {42, 17, 23, 7, 89, 5, 31};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the number of elements
// Call the function to find the smallest number
int minNumber = findSmallest(numbers, size);
// Display the result
cout << "The smallest number in the array is: " << minNumber << endl;
return 0; // End of the program
}
Salida
The smallest number in the array is: 5
Comparte este ejercicio C++