From 62ac28b9fc3d409015b281454dced7d4acd31cd8 Mon Sep 17 00:00:00 2001 From: "exercism-solutions-syncer[bot]" <211797793+exercism-solutions-syncer[bot]@users.noreply.github.com> Date: Sun, 21 Jun 2026 21:53:37 +0000 Subject: [PATCH] [Sync Iteration] cpp/binary-search/1 --- .../cpp/binary-search/1/binary_search.cpp | 39 +++++++++++++++++++ solutions/cpp/binary-search/1/binary_search.h | 11 ++++++ 2 files changed, 50 insertions(+) create mode 100644 solutions/cpp/binary-search/1/binary_search.cpp create mode 100644 solutions/cpp/binary-search/1/binary_search.h diff --git a/solutions/cpp/binary-search/1/binary_search.cpp b/solutions/cpp/binary-search/1/binary_search.cpp new file mode 100644 index 0000000..4d86427 --- /dev/null +++ b/solutions/cpp/binary-search/1/binary_search.cpp @@ -0,0 +1,39 @@ +#include "binary_search.h" +#include + +namespace binary_search { + +std::size_t find(const std::vector& data, int value) { + // 1. Caso: Si el vector está vacío, no hay nada que buscar + if (data.empty()) { + throw std::domain_error("La lista está vacía"); + } + + // 2. Control de límites para evitar underflows + int left = 0; + int right = static_cast(data.size()) - 1; + + while (left <= right) { + // Optimización para evitar overflow + int mid = left + (right - left) / 2; + + // ¡Aqui lo encontramos! + if (data[mid] == value) { + return static_cast(mid); + } + + // Si el valor del centro es mayor, descartamos la mitad derecha + if (data[mid] > value) { + right = mid - 1; + } + // Si el valor del centro es menor, descartamos la mitad izquierda + else { + left = mid + 1; + } + } + + // 3. Si salimos del bucle, los límites se cruzaron: el valor no existe + throw std::domain_error("El valor buscado no existe en la lista"); +} + +} diff --git a/solutions/cpp/binary-search/1/binary_search.h b/solutions/cpp/binary-search/1/binary_search.h new file mode 100644 index 0000000..1f706e6 --- /dev/null +++ b/solutions/cpp/binary-search/1/binary_search.h @@ -0,0 +1,11 @@ +#pragma once +#include +#include + +namespace binary_search { + + // Busca un valor en un vector ordenado y devuelve su índice. + // Lanza std::domain_error si el valor no existe. + std::size_t find(const std::vector& data, int value); + +}