Grupo
Algoritmos de Búsqueda y Ordenación en C++
Ojetivo
Escriba una función llamada binarySearch que tome un array ordenado, el número de elementos y un valor objetivo a buscar. Dentro de la función, implemente el algoritmo de búsqueda binaria mediante un bucle. En la función principal, defina un array ordenado de enteros y utilice la función binarySearch para localizar un valor. Muestre el resultado imprimiendo el índice del elemento si se encuentra o un mensaje indicando que no se encontró.
Desarrolle una función que realice una búsqueda binaria en un array ordenado.
Ejemplo de Código C++
Mostrar Código C++
#include <iostream> // Include the input-output stream library
using namespace std;
// Function to perform binary search on a sorted array
int binarySearch(int arr[], int size, int target) {
int low = 0; // Start index of the search range
int high = size - 1; // End index of the search range
// Continue the loop while the range is valid
while (low <= high) {
int mid = low + (high - low) / 2; // Calculate the middle index
// If the element is found at mid
if (arr[mid] == target) {
return mid; // Return the index where the target is found
}
// If the target is smaller, it lies in the left half
else if (target < arr[mid]) {
high = mid - 1; // Adjust the end of the range
}
// If the target is larger, it lies in the right half
else {
low = mid + 1; // Adjust the start of the range
}
}
return -1; // Return -1 if the target is not found
}
int main() {
// Define a sorted array of integers
int numbers[] = {3, 6, 9, 12, 15, 18, 21};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate number of elements
int target = 15; // Value to search in the array
// Call the binarySearch function
int index = binarySearch(numbers, size, target);
// Display the result
if (index != -1) {
cout << "Element found at index " << index << endl;
} else {
cout << "Element not found in the array." << endl;
}
return 0; // Indicate successful program termination
}
Salida
Element found at index 4
Comparte este ejercicio C++