Grupo
Algoritmos de Búsqueda y Ordenación en C++
Ojetivo
Escriba un programa en C++ que realice una búsqueda lineal para encontrar un elemento en un array. La función debe devolver el índice del elemento si se encuentra, o -1 si no está en el array. Implemente este algoritmo de búsqueda y pruébelo con un array de ejemplo.
Implemente un algoritmo de búsqueda lineal.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the input-output stream library
using namespace std;
// Function to perform linear search on an array
int linearSearch(int arr[], int size, int target) {
// Loop through each element in the array
for (int i = 0; i < size; i++) {
if (arr[i] == target) { // Check if the current element matches the target
return i; // Return the index of the target element if found
}
}
return -1; // Return -1 if the target element is not found in the array
}
int main() {
// Define an array of integers
int numbers[] = {15, 27, 38, 49, 56, 72, 91};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate the number of elements
// Define the target element to search for
int target = 49;
// Call the linearSearch function
int result = linearSearch(numbers, size, target);
// Check if the target was found and display the result
if (result != -1) {
cout << "Element found at index: " << result << endl; // Element found, display its index
} else {
cout << "Element not found in the array." << endl; // Element not found, display message
}
return 0; // End of the program
}
Salida
Element found at index: 3
Comparte este ejercicio C++